blob: 6f2fc5e0c434b15dd4d1689566f850d4e38ce0e0 [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
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000068 for (llvm::tie(I, End) = NS->getUsingDirectives(); 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 Carlssone136e0e2009-06-26 06:29:23 +0000142 NamedDecl *ND = (*I)->getUnderlyingDecl();
Anders Carlsson58badb72009-06-26 05:26:50 +0000143 if (isa<FunctionDecl>(ND))
144 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregore53060f2009-06-25 22:08:12 +0000145 else
Anders Carlsson58badb72009-06-26 05:26:50 +0000146 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000147 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000148
Anders Carlssone136e0e2009-06-26 06:29:23 +0000149 NamedDecl *ND = (*Last)->getUnderlyingDecl();
Anders Carlsson58badb72009-06-26 05:26:50 +0000150 if (isa<FunctionDecl>(ND))
151 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregore53060f2009-06-25 22:08:12 +0000152 else
Anders Carlsson58badb72009-06-26 05:26:50 +0000153 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000154 }
155
156 // If we had more than one function, we built an overload
157 // set. Return it.
158 if (Ovl)
159 return Ovl;
160 }
161
162 return *I;
163}
164
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000165/// Merges together multiple LookupResults dealing with duplicated Decl's.
166static Sema::LookupResult
167MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
168 typedef Sema::LookupResult LResult;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000169 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000170
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000171 // Remove duplicated Decl pointing at same Decl, by storing them in
172 // associative collection. This might be case for code like:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000173 //
174 // namespace A { int i; }
175 // namespace B { using namespace A; }
176 // namespace C { using namespace A; }
177 //
178 // void foo() {
179 // using namespace B;
180 // using namespace C;
181 // ++i; // finds A::i, from both namespace B and C at global scope
182 // }
183 //
184 // C++ [namespace.qual].p3:
185 // The same declaration found more than once is not an ambiguity
186 // (because it is still a unique declaration).
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000187 DeclsSetTy FoundDecls;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000188
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000189 // Counter of tag names, and functions for resolving ambiguity
190 // and name hiding.
191 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000192
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000193 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
194
195 // No name lookup results, return early.
196 if (I == End) return LResult::CreateLookupResult(Context, 0);
197
198 // Keep track of the tag declaration we found. We only use this if
199 // we find a single tag declaration.
200 TagDecl *TagFound = 0;
201
202 for (; I != End; ++I) {
203 switch (I->getKind()) {
204 case LResult::NotFound:
205 assert(false &&
206 "Should be always successful name lookup result here.");
207 break;
208
209 case LResult::AmbiguousReference:
210 case LResult::AmbiguousBaseSubobjectTypes:
211 case LResult::AmbiguousBaseSubobjects:
212 assert(false && "Shouldn't get ambiguous lookup here.");
213 break;
214
215 case LResult::Found: {
Anders Carlssone136e0e2009-06-26 06:29:23 +0000216 NamedDecl *ND = I->getAsDecl()->getUnderlyingDecl();
Anders Carlssonbc13ab22009-06-26 03:54:13 +0000217
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) {
Anders Carlssone136e0e2009-06-26 06:29:23 +0000328 if (D)
329 D = D->getUnderlyingDecl();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000330
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000331 LookupResult Result;
332 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
333 OverloadedDeclSingleDecl : SingleDecl;
334 Result.First = reinterpret_cast<uintptr_t>(D);
335 Result.Last = 0;
336 Result.Context = &Context;
337 return Result;
338}
339
Douglas Gregor4bb64e72009-01-15 02:19:31 +0000340/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000341Sema::LookupResult
342Sema::LookupResult::CreateLookupResult(ASTContext &Context,
343 IdentifierResolver::iterator F,
344 IdentifierResolver::iterator L) {
345 LookupResult Result;
346 Result.Context = &Context;
347
Douglas Gregore53060f2009-06-25 22:08:12 +0000348 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000349 IdentifierResolver::iterator Next = F;
350 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000351 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000352 Result.StoredKind = OverloadedDeclFromIdResolver;
353 Result.First = F.getAsOpaqueValue();
354 Result.Last = L.getAsOpaqueValue();
355 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000356 }
357 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000358
Anders Carlssone136e0e2009-06-26 06:29:23 +0000359 NamedDecl *D = *F;
360 if (D)
361 D = D->getUnderlyingDecl();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000362
Douglas Gregor69d993a2009-01-17 01:13:24 +0000363 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000364 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000365 Result.Last = 0;
366 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000367}
368
Douglas Gregor69d993a2009-01-17 01:13:24 +0000369Sema::LookupResult
370Sema::LookupResult::CreateLookupResult(ASTContext &Context,
371 DeclContext::lookup_iterator F,
372 DeclContext::lookup_iterator L) {
373 LookupResult Result;
374 Result.Context = &Context;
375
Douglas Gregore53060f2009-06-25 22:08:12 +0000376 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000377 DeclContext::lookup_iterator Next = F;
378 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000379 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000380 Result.StoredKind = OverloadedDeclFromDeclContext;
381 Result.First = reinterpret_cast<uintptr_t>(F);
382 Result.Last = reinterpret_cast<uintptr_t>(L);
383 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000384 }
385 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000386
Anders Carlssone136e0e2009-06-26 06:29:23 +0000387 NamedDecl *D = *F;
388 if (D)
389 D = D->getUnderlyingDecl();
390
Douglas Gregor69d993a2009-01-17 01:13:24 +0000391 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000392 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000393 Result.Last = 0;
394 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000395}
396
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000397/// @brief Determine the result of name lookup.
398Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
399 switch (StoredKind) {
400 case SingleDecl:
401 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
402
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000403 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000404 case OverloadedDeclFromIdResolver:
405 case OverloadedDeclFromDeclContext:
406 return FoundOverloaded;
407
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000408 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000409 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000410
411 case AmbiguousLookupStoresDecls:
412 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000413 }
414
Douglas Gregor7176fff2009-01-15 00:26:24 +0000415 // We can't ever get here.
416 return NotFound;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000417}
418
419/// @brief Converts the result of name lookup into a single (possible
420/// NULL) pointer to a declaration.
421///
422/// The resulting declaration will either be the declaration we found
423/// (if only a single declaration was found), an
424/// OverloadedFunctionDecl (if an overloaded function was found), or
425/// NULL (if no declaration was found). This conversion must not be
426/// used anywhere where name lookup could result in an ambiguity.
427///
428/// The OverloadedFunctionDecl conversion is meant as a stop-gap
429/// solution, since it causes the OverloadedFunctionDecl to be
430/// leaked. FIXME: Eventually, there will be a better way to iterate
431/// over the set of overloaded functions returned by name lookup.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000432NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000433 switch (StoredKind) {
434 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000435 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000436
437 case OverloadedDeclFromIdResolver:
438 return MaybeConstructOverloadSet(*Context,
439 IdentifierResolver::iterator::getFromOpaqueValue(First),
440 IdentifierResolver::iterator::getFromOpaqueValue(Last));
441
442 case OverloadedDeclFromDeclContext:
443 return MaybeConstructOverloadSet(*Context,
444 reinterpret_cast<DeclContext::lookup_iterator>(First),
445 reinterpret_cast<DeclContext::lookup_iterator>(Last));
446
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000447 case OverloadedDeclSingleDecl:
448 return reinterpret_cast<OverloadedFunctionDecl*>(First);
449
450 case AmbiguousLookupStoresDecls:
451 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000452 assert(false &&
453 "Name lookup returned an ambiguity that could not be handled");
454 break;
455 }
456
457 return 0;
458}
459
Douglas Gregor7176fff2009-01-15 00:26:24 +0000460/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000461/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000462BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000463 if (StoredKind == AmbiguousLookupStoresBasePaths)
464 return reinterpret_cast<BasePaths *>(First);
465 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000466}
467
Douglas Gregord8635172009-02-02 21:35:47 +0000468Sema::LookupResult::iterator::reference
469Sema::LookupResult::iterator::operator*() const {
470 switch (Result->StoredKind) {
471 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000472 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000473
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000474 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000475 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000476
Douglas Gregord8635172009-02-02 21:35:47 +0000477 case OverloadedDeclFromIdResolver:
478 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
479
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000480 case AmbiguousLookupStoresBasePaths:
Douglas Gregor31a19b62009-04-01 21:51:26 +0000481 if (Result->Last)
482 return *reinterpret_cast<NamedDecl**>(Current);
483
484 // Fall through to handle the DeclContext::lookup_iterator we're
485 // storing.
486
487 case OverloadedDeclFromDeclContext:
488 case AmbiguousLookupStoresDecls:
489 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000490 }
491
492 return 0;
493}
494
495Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
496 switch (Result->StoredKind) {
497 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000498 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000499 break;
500
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000501 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000502 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000503 ++I;
504 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000505 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000506 }
507
Douglas Gregord8635172009-02-02 21:35:47 +0000508 case OverloadedDeclFromIdResolver: {
509 IdentifierResolver::iterator I
510 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
511 ++I;
512 Current = I.getAsOpaqueValue();
513 break;
514 }
515
Douglas Gregor31a19b62009-04-01 21:51:26 +0000516 case AmbiguousLookupStoresBasePaths:
517 if (Result->Last) {
518 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
519 ++I;
520 Current = reinterpret_cast<uintptr_t>(I);
521 break;
522 }
523 // Fall through to handle the DeclContext::lookup_iterator we're
524 // storing.
525
526 case OverloadedDeclFromDeclContext:
527 case AmbiguousLookupStoresDecls: {
Douglas Gregord8635172009-02-02 21:35:47 +0000528 DeclContext::lookup_iterator I
529 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
530 ++I;
531 Current = reinterpret_cast<uintptr_t>(I);
532 break;
533 }
Douglas Gregord8635172009-02-02 21:35:47 +0000534 }
535
536 return *this;
537}
538
539Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000540 switch (StoredKind) {
541 case SingleDecl:
542 case OverloadedDeclFromIdResolver:
543 case OverloadedDeclFromDeclContext:
544 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000545 return iterator(this, First);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000546
547 case OverloadedDeclSingleDecl: {
548 OverloadedFunctionDecl * Ovl =
549 reinterpret_cast<OverloadedFunctionDecl*>(First);
550 return iterator(this,
551 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
552 }
553
554 case AmbiguousLookupStoresBasePaths:
555 if (Last)
556 return iterator(this,
557 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
558 else
559 return iterator(this,
560 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
561 }
562
563 // Required to suppress GCC warning.
564 return iterator();
Douglas Gregord8635172009-02-02 21:35:47 +0000565}
566
567Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000568 switch (StoredKind) {
569 case SingleDecl:
570 case OverloadedDeclFromIdResolver:
571 case OverloadedDeclFromDeclContext:
572 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000573 return iterator(this, Last);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000574
575 case OverloadedDeclSingleDecl: {
576 OverloadedFunctionDecl * Ovl =
577 reinterpret_cast<OverloadedFunctionDecl*>(First);
578 return iterator(this,
579 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
580 }
581
582 case AmbiguousLookupStoresBasePaths:
583 if (Last)
584 return iterator(this,
585 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
586 else
587 return iterator(this, reinterpret_cast<uintptr_t>(
588 getBasePaths()->front().Decls.second));
589 }
590
591 // Required to suppress GCC warning.
592 return iterator();
593}
594
595void Sema::LookupResult::Destroy() {
596 if (BasePaths *Paths = getBasePaths())
597 delete Paths;
598 else if (getKind() == AmbiguousReference)
599 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregord8635172009-02-02 21:35:47 +0000600}
601
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000602static void
603CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
604 DeclarationName Name, Sema::LookupNameKind NameKind,
605 unsigned IDNS, LookupResultsTy &Results,
606 UsingDirectivesTy *UDirs = 0) {
607
608 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
609
610 // Perform qualified name lookup into the LookupCtx.
611 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000612 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000613 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
614 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
615 break;
616 }
617
618 if (UDirs) {
619 // For each UsingDirectiveDecl, which common ancestor is equal
620 // to NS, we preform qualified name lookup into namespace nominated by it.
621 UsingDirectivesTy::const_iterator UI, UEnd;
622 llvm::tie(UI, UEnd) =
623 std::equal_range(UDirs->begin(), UDirs->end(), NS,
624 UsingDirAncestorCompare());
625
626 for (; UI != UEnd; ++UI)
627 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
628 Name, NameKind, IDNS, Results);
629 }
630}
631
632static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000633 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000634 return Ctx->isFileContext();
635 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000636}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000637
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000638std::pair<bool, Sema::LookupResult>
639Sema::CppLookupName(Scope *S, DeclarationName Name,
640 LookupNameKind NameKind, bool RedeclarationOnly) {
641 assert(getLangOptions().CPlusPlus &&
642 "Can perform only C++ lookup");
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000643 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000644 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000645 Scope *Initial = S;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000646 DeclContext *OutOfLineCtx = 0;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000647 IdentifierResolver::iterator
648 I = IdResolver.begin(Name),
649 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000650
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000651 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000652 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000653 // ...During unqualified name lookup (3.4.1), the names appear as if
654 // they were declared in the nearest enclosing namespace which contains
655 // both the using-directive and the nominated namespace.
656 // [Note: in this context, “contains” means “contains directly or
657 // indirectly”.
658 //
659 // For example:
660 // namespace A { int i; }
661 // void foo() {
662 // int i;
663 // {
664 // using namespace A;
665 // ++i; // finds local 'i', A::i appears at global scope
666 // }
667 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000668 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000669 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000670 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000671 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000672 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
673 // We found something. Look for anything else in our scope
674 // with this same name and in an acceptable identifier
675 // namespace, so that we can construct an overload set if we
676 // need to.
677 IdentifierResolver::iterator LastI = I;
678 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000679 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000680 break;
681 }
682 LookupResult Result =
683 LookupResult::CreateLookupResult(Context, I, LastI);
684 return std::make_pair(true, Result);
685 }
686 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000687 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
688 LookupResult R;
689 // Perform member lookup into struct.
Mike Stump390b4cc2009-05-16 07:39:55 +0000690 // FIXME: In some cases, we know that every name that could be found by
691 // this qualified name lookup will also be on the identifier chain. For
692 // example, inside a class without any base classes, we never need to
693 // perform qualified lookup because all of the members are on top of the
694 // identifier chain.
Douglas Gregor551f48c2009-03-27 04:21:56 +0000695 if (isa<RecordDecl>(Ctx)) {
696 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000697 if (R)
Douglas Gregor551f48c2009-03-27 04:21:56 +0000698 return std::make_pair(true, R);
699 }
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000700 if (Ctx->getParent() != Ctx->getLexicalParent()
701 || isa<CXXMethodDecl>(Ctx)) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000702 // It is out of line defined C++ method or struct, we continue
703 // doing name lookup in parent context. Once we will find namespace
704 // or translation-unit we save it for possible checking
705 // using-directives later.
706 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
707 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregor551f48c2009-03-27 04:21:56 +0000708 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000709 if (R)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000710 return std::make_pair(true, R);
711 }
712 }
713 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000714 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000715
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000716 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000717 // nominated namespaces by those using-directives.
Mike Stump390b4cc2009-05-16 07:39:55 +0000718 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
719 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
720 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000721 UsingDirectivesTy UDirs;
722 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000723 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregor6ab35242009-04-09 21:40:53 +0000724 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000725
726 // Sort heapified UsingDirectiveDecls.
Douglas Gregorb738e082009-05-18 22:06:54 +0000727 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000728
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000729 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000730 // Unqualified name lookup in C++ requires looking into scopes
731 // that aren't strictly lexical, and therefore we walk through the
732 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000733
734 LookupResultsTy LookupResults;
Sebastian Redl22460502009-02-07 00:15:38 +0000735 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000736 "We should have been looking only at file context here already.");
737 bool LookedInCtx = false;
738 LookupResult Result;
739 while (OutOfLineCtx &&
740 OutOfLineCtx != S->getEntity() &&
741 OutOfLineCtx->isNamespace()) {
742 LookedInCtx = true;
743
744 // Look into context considering using-directives.
745 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
746 LookupResults, &UDirs);
747
748 if ((Result = MergeLookupResults(Context, LookupResults)) ||
749 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
750 return std::make_pair(true, Result);
751
752 OutOfLineCtx = OutOfLineCtx->getParent();
753 }
754
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000755 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000756 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
757 assert(Ctx && Ctx->isFileContext() &&
758 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000759
760 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000761 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000762 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
763 // We found something. Look for anything else in our scope
764 // with this same name and in an acceptable identifier
765 // namespace, so that we can construct an overload set if we
766 // need to.
767 IdentifierResolver::iterator LastI = I;
768 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000769 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000770 break;
771 }
772
773 // We store name lookup result, and continue trying to look into
774 // associated context, and maybe namespaces nominated by
775 // using-directives.
776 LookupResults.push_back(
777 LookupResult::CreateLookupResult(Context, I, LastI));
778 break;
779 }
780 }
781
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000782 LookedInCtx = true;
783 // Look into context considering using-directives.
784 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
785 LookupResults, &UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000786
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000787 if ((Result = MergeLookupResults(Context, LookupResults)) ||
788 (RedeclarationOnly && !Ctx->isTransparentContext()))
789 return std::make_pair(true, Result);
790 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000791
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000792 if (!(LookedInCtx || LookupResults.empty())) {
793 // We didn't Performed lookup in Scope entity, so we return
794 // result form IdentifierResolver.
795 assert((LookupResults.size() == 1) && "Wrong size!");
796 return std::make_pair(true, LookupResults.front());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000797 }
798 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000799}
800
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000801/// @brief Perform unqualified name lookup starting from a given
802/// scope.
803///
804/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
805/// used to find names within the current scope. For example, 'x' in
806/// @code
807/// int x;
808/// int f() {
809/// return x; // unqualified name look finds 'x' in the global scope
810/// }
811/// @endcode
812///
813/// Different lookup criteria can find different names. For example, a
814/// particular scope can have both a struct and a function of the same
815/// name, and each can be found by certain lookup criteria. For more
816/// information about lookup criteria, see the documentation for the
817/// class LookupCriteria.
818///
819/// @param S The scope from which unqualified name lookup will
820/// begin. If the lookup criteria permits, name lookup may also search
821/// in the parent scopes.
822///
823/// @param Name The name of the entity that we are searching for.
824///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000825/// @param Loc If provided, the source location where we're performing
826/// name lookup. At present, this is only used to produce diagnostics when
827/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000828///
829/// @returns The result of name lookup, which includes zero or more
830/// declarations and possibly additional information used to diagnose
831/// ambiguities.
832Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000833Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000834 bool RedeclarationOnly, bool AllowBuiltinCreation,
835 SourceLocation Loc) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000836 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000837
838 if (!getLangOptions().CPlusPlus) {
839 // Unqualified name lookup in C/Objective-C is purely lexical, so
840 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000841 unsigned IDNS = 0;
842 switch (NameKind) {
843 case Sema::LookupOrdinaryName:
844 IDNS = Decl::IDNS_Ordinary;
845 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000846
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000847 case Sema::LookupTagName:
848 IDNS = Decl::IDNS_Tag;
849 break;
850
851 case Sema::LookupMemberName:
852 IDNS = Decl::IDNS_Member;
853 break;
854
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000855 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000856 case Sema::LookupNestedNameSpecifierName:
857 case Sema::LookupNamespaceName:
858 assert(false && "C does not perform these kinds of name lookup");
859 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000860
861 case Sema::LookupRedeclarationWithLinkage:
862 // Find the nearest non-transparent declaration scope.
863 while (!(S->getFlags() & Scope::DeclScope) ||
864 (S->getEntity() &&
865 static_cast<DeclContext *>(S->getEntity())
866 ->isTransparentContext()))
867 S = S->getParent();
868 IDNS = Decl::IDNS_Ordinary;
869 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000870
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000871 case Sema::LookupObjCProtocolName:
872 IDNS = Decl::IDNS_ObjCProtocol;
873 break;
874
875 case Sema::LookupObjCImplementationName:
876 IDNS = Decl::IDNS_ObjCImplementation;
877 break;
878
879 case Sema::LookupObjCCategoryImplName:
880 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000881 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000882 }
883
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000884 // Scan up the scope chain looking for a decl that matches this
885 // identifier that is in the appropriate namespace. This search
886 // should not take long, as shadowing of names is uncommon, and
887 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000888 bool LeftStartingScope = false;
889
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000890 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
891 IEnd = IdResolver.end();
892 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000893 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000894 if (NameKind == LookupRedeclarationWithLinkage) {
895 // Determine whether this (or a previous) declaration is
896 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000897 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000898 LeftStartingScope = true;
899
900 // If we found something outside of our starting scope that
901 // does not have linkage, skip it.
902 if (LeftStartingScope && !((*I)->hasLinkage()))
903 continue;
904 }
905
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000906 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000907 // If this declaration has the "overloadable" attribute, we
908 // might have a set of overloaded functions.
909
910 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000911 while (!(S->getFlags() & Scope::DeclScope) ||
912 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000913 S = S->getParent();
914
915 // Find the last declaration in this scope (with the same
916 // name, naturally).
917 IdentifierResolver::iterator LastI = I;
918 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000919 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000920 break;
921 }
922
923 return LookupResult::CreateLookupResult(Context, I, LastI);
924 }
925
926 // We have a single lookup result.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000927 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000928 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000929 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000930 // Perform C++ unqualified name lookup.
931 std::pair<bool, LookupResult> MaybeResult =
932 CppLookupName(S, Name, NameKind, RedeclarationOnly);
933 if (MaybeResult.first)
934 return MaybeResult.second;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000935 }
936
937 // If we didn't find a use of this identifier, and if the identifier
938 // corresponds to a compiler builtin, create the decl object for the builtin
939 // now, injecting it into translation unit scope, and return it.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000940 if (NameKind == LookupOrdinaryName ||
941 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000942 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000943 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000944 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000945 if (unsigned BuiltinID = II->getBuiltinID()) {
946 // In C++, we don't have any predefined library functions like
947 // 'malloc'. Instead, we'll just error.
948 if (getLangOptions().CPlusPlus &&
949 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
950 return LookupResult::CreateLookupResult(Context, 0);
951
Douglas Gregor69d993a2009-01-17 01:13:24 +0000952 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000953 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000954 S, RedeclarationOnly, Loc));
955 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000956 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000957 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000958 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000959}
960
961/// @brief Perform qualified name lookup into a given context.
962///
963/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
964/// names when the context of those names is explicit specified, e.g.,
965/// "std::vector" or "x->member".
966///
967/// Different lookup criteria can find different names. For example, a
968/// particular scope can have both a struct and a function of the same
969/// name, and each can be found by certain lookup criteria. For more
970/// information about lookup criteria, see the documentation for the
971/// class LookupCriteria.
972///
973/// @param LookupCtx The context in which qualified name lookup will
974/// search. If the lookup criteria permits, name lookup may also search
975/// in the parent contexts or (for C++ classes) base classes.
976///
977/// @param Name The name of the entity that we are searching for.
978///
979/// @param Criteria The criteria that this routine will use to
980/// determine which names are visible and which names will be
981/// found. Note that name lookup will find a name that is visible by
982/// the given criteria, but the entity itself may not be semantically
983/// correct or even the kind of entity expected based on the
984/// lookup. For example, searching for a nested-name-specifier name
985/// might result in an EnumDecl, which is visible but is not permitted
986/// as a nested-name-specifier in C++03.
987///
988/// @returns The result of name lookup, which includes zero or more
989/// declarations and possibly additional information used to diagnose
990/// ambiguities.
991Sema::LookupResult
992Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000993 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000994 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
995
Douglas Gregor69d993a2009-01-17 01:13:24 +0000996 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000997
998 // If we're performing qualified name lookup (e.g., lookup into a
999 // struct), find fields as part of ordinary name lookup.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001000 unsigned IDNS
1001 = getIdentifierNamespacesFromLookupNameKind(NameKind,
1002 getLangOptions().CPlusPlus);
1003 if (NameKind == LookupOrdinaryName)
1004 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001005
1006 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001007 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001008 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001009 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001010 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001011
Douglas Gregor7176fff2009-01-15 00:26:24 +00001012 // If this isn't a C++ class or we aren't allowed to look into base
1013 // classes, we're done.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001014 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001015 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001016
1017 // Perform lookup into our base classes.
1018 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001019 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +00001020
1021 // Look for this member in our base classes
1022 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001023 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001024 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001025
1026 // C++ [class.member.lookup]p2:
1027 // [...] If the resulting set of declarations are not all from
1028 // sub-objects of the same type, or the set has a nonstatic member
1029 // and includes members from distinct sub-objects, there is an
1030 // ambiguity and the program is ill-formed. Otherwise that set is
1031 // the result of the lookup.
1032 // FIXME: support using declarations!
1033 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001034 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001035 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1036 Path != PathEnd; ++Path) {
1037 const BasePathElement &PathElement = Path->back();
1038
1039 // Determine whether we're looking at a distinct sub-object or not.
1040 if (SubobjectType.isNull()) {
1041 // This is the first subobject we've looked at. Record it's type.
1042 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1043 SubobjectNumber = PathElement.SubobjectNumber;
1044 } else if (SubobjectType
1045 != Context.getCanonicalType(PathElement.Base->getType())) {
1046 // We found members of the given name in two subobjects of
1047 // different types. This lookup is ambiguous.
1048 BasePaths *PathsOnHeap = new BasePaths;
1049 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001050 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001051 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1052 // We have a different subobject of the same type.
1053
1054 // C++ [class.member.lookup]p5:
1055 // A static member, a nested type or an enumerator defined in
1056 // a base class T can unambiguously be found even if an object
1057 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001058 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001059 if (isa<VarDecl>(FirstDecl) ||
1060 isa<TypeDecl>(FirstDecl) ||
1061 isa<EnumConstantDecl>(FirstDecl))
1062 continue;
1063
1064 if (isa<CXXMethodDecl>(FirstDecl)) {
1065 // Determine whether all of the methods are static.
1066 bool AllMethodsAreStatic = true;
1067 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1068 Func != Path->Decls.second; ++Func) {
1069 if (!isa<CXXMethodDecl>(*Func)) {
1070 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1071 break;
1072 }
1073
1074 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1075 AllMethodsAreStatic = false;
1076 break;
1077 }
1078 }
1079
1080 if (AllMethodsAreStatic)
1081 continue;
1082 }
1083
1084 // We have found a nonstatic member name in multiple, distinct
1085 // subobjects. Name lookup is ambiguous.
1086 BasePaths *PathsOnHeap = new BasePaths;
1087 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001088 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001089 }
1090 }
1091
1092 // Lookup in a base class succeeded; return these results.
1093
1094 // If we found a function declaration, return an overload set.
Douglas Gregore53060f2009-06-25 22:08:12 +00001095 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
Douglas Gregor69d993a2009-01-17 01:13:24 +00001096 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-01-15 00:26:24 +00001097 Paths.front().Decls.first, Paths.front().Decls.second);
1098
1099 // We found a non-function declaration; return a single declaration.
Douglas Gregor69d993a2009-01-17 01:13:24 +00001100 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001101}
1102
1103/// @brief Performs name lookup for a name that was parsed in the
1104/// source code, and may contain a C++ scope specifier.
1105///
1106/// This routine is a convenience routine meant to be called from
1107/// contexts that receive a name and an optional C++ scope specifier
1108/// (e.g., "N::M::x"). It will then perform either qualified or
1109/// unqualified name lookup (with LookupQualifiedName or LookupName,
1110/// respectively) on the given name and return those results.
1111///
1112/// @param S The scope from which unqualified name lookup will
1113/// begin.
1114///
1115/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1116///
1117/// @param Name The name of the entity that name lookup will
1118/// search for.
1119///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001120/// @param Loc If provided, the source location where we're performing
1121/// name lookup. At present, this is only used to produce diagnostics when
1122/// C library functions (like "malloc") are implicitly declared.
1123///
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001124/// @returns The result of qualified or unqualified name lookup.
1125Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001126Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1127 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001128 bool RedeclarationOnly, bool AllowBuiltinCreation,
1129 SourceLocation Loc) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00001130 if (SS && (SS->isSet() || SS->isInvalid())) {
1131 // If the scope specifier is invalid, don't even look for
1132 // anything.
1133 if (SS->isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001134 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001135
Douglas Gregor42af25f2009-05-11 19:58:34 +00001136 assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1137
1138 if (isDependentScopeSpecifier(*SS)) {
1139 // Determine whether we are looking into the current
1140 // instantiation.
1141 NestedNameSpecifier *NNS
1142 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1143 CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1144 assert(Current && "Bad dependent scope specifier");
1145
1146 // We nested name specifier refers to the current instantiation,
1147 // so now we will look for a member of the current instantiation
1148 // (C++0x [temp.dep.type]).
1149 unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1150 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001151 for (llvm::tie(I, E) = Current->lookup(Name); I != E; ++I)
Douglas Gregor42af25f2009-05-11 19:58:34 +00001152 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1153 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001154 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001155
1156 if (RequireCompleteDeclContext(*SS))
1157 return LookupResult::CreateLookupResult(Context, 0);
1158
1159 return LookupQualifiedName(computeDeclContext(*SS),
1160 Name, NameKind, RedeclarationOnly);
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001161 }
1162
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001163 LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly,
1164 AllowBuiltinCreation, Loc));
1165
1166 return(result);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001167}
1168
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001169
Douglas Gregor7176fff2009-01-15 00:26:24 +00001170/// @brief Produce a diagnostic describing the ambiguity that resulted
1171/// from name lookup.
1172///
1173/// @param Result The ambiguous name lookup result.
1174///
1175/// @param Name The name of the entity that name lookup was
1176/// searching for.
1177///
1178/// @param NameLoc The location of the name within the source code.
1179///
1180/// @param LookupRange A source range that provides more
1181/// source-location information concerning the lookup itself. For
1182/// example, this range might highlight a nested-name-specifier that
1183/// precedes the name.
1184///
1185/// @returns true
1186bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1187 SourceLocation NameLoc,
1188 SourceRange LookupRange) {
1189 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1190
Douglas Gregor31a19b62009-04-01 21:51:26 +00001191 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001192 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1193 QualType SubobjectType = Paths->front().back().Base->getType();
1194 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1195 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1196 << LookupRange;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001197
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001198 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregor31a19b62009-04-01 21:51:26 +00001199 while (isa<CXXMethodDecl>(*Found) &&
1200 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001201 ++Found;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001202
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001203 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1204
Douglas Gregor31a19b62009-04-01 21:51:26 +00001205 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001206 return true;
1207 }
1208
1209 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1210 "Unhandled form of name lookup ambiguity");
1211
1212 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1213 << Name << LookupRange;
1214
1215 std::set<Decl *> DeclsPrinted;
1216 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1217 Path != PathEnd; ++Path) {
1218 Decl *D = *Path->Decls.first;
1219 if (DeclsPrinted.insert(D).second)
1220 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1221 }
1222
Douglas Gregor31a19b62009-04-01 21:51:26 +00001223 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001224 return true;
1225 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001226 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1227
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001228 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregor31a19b62009-04-01 21:51:26 +00001229 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001230
Chris Lattner48458d22009-02-03 21:29:32 +00001231 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001232 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001233
Douglas Gregor31a19b62009-04-01 21:51:26 +00001234 Result.Destroy();
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001235 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001236 }
1237
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001238 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001239
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001240 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001241 return true;
1242}
Douglas Gregorfa047642009-02-04 00:32:51 +00001243
1244// \brief Add the associated classes and namespaces for
1245// argument-dependent lookup with an argument of class type
1246// (C++ [basic.lookup.koenig]p2).
1247static void
1248addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1249 ASTContext &Context,
1250 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001251 Sema::AssociatedClassSet &AssociatedClasses,
1252 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001253 // C++ [basic.lookup.koenig]p2:
1254 // [...]
1255 // -- If T is a class type (including unions), its associated
1256 // classes are: the class itself; the class of which it is a
1257 // member, if any; and its direct and indirect base
1258 // classes. Its associated namespaces are the namespaces in
1259 // which its associated classes are defined.
1260
1261 // Add the class of which it is a member, if any.
1262 DeclContext *Ctx = Class->getDeclContext();
1263 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1264 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001265 // Add the associated namespace for this class.
1266 while (Ctx->isRecord())
1267 Ctx = Ctx->getParent();
1268 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1269 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001270 else if (Ctx->isTranslationUnit())
1271 GlobalScope = true;
1272
Douglas Gregorfa047642009-02-04 00:32:51 +00001273 // Add the class itself. If we've already seen this class, we don't
1274 // need to visit base classes.
1275 if (!AssociatedClasses.insert(Class))
1276 return;
1277
1278 // FIXME: Handle class template specializations
1279
1280 // Add direct and indirect base classes along with their associated
1281 // namespaces.
1282 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1283 Bases.push_back(Class);
1284 while (!Bases.empty()) {
1285 // Pop this class off the stack.
1286 Class = Bases.back();
1287 Bases.pop_back();
1288
1289 // Visit the base classes.
1290 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1291 BaseEnd = Class->bases_end();
1292 Base != BaseEnd; ++Base) {
1293 const RecordType *BaseType = Base->getType()->getAsRecordType();
1294 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1295 if (AssociatedClasses.insert(BaseDecl)) {
1296 // Find the associated namespace for this base class.
1297 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1298 while (BaseCtx->isRecord())
1299 BaseCtx = BaseCtx->getParent();
1300 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1301 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001302 else if (BaseCtx->isTranslationUnit())
1303 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001304
1305 // Make sure we visit the bases of this base class.
1306 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1307 Bases.push_back(BaseDecl);
1308 }
1309 }
1310 }
1311}
1312
1313// \brief Add the associated classes and namespaces for
1314// argument-dependent lookup with an argument of type T
1315// (C++ [basic.lookup.koenig]p2).
1316static void
1317addAssociatedClassesAndNamespaces(QualType T,
1318 ASTContext &Context,
1319 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001320 Sema::AssociatedClassSet &AssociatedClasses,
1321 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001322 // C++ [basic.lookup.koenig]p2:
1323 //
1324 // For each argument type T in the function call, there is a set
1325 // of zero or more associated namespaces and a set of zero or more
1326 // associated classes to be considered. The sets of namespaces and
1327 // classes is determined entirely by the types of the function
1328 // arguments (and the namespace of any template template
1329 // argument). Typedef names and using-declarations used to specify
1330 // the types do not contribute to this set. The sets of namespaces
1331 // and classes are determined in the following way:
1332 T = Context.getCanonicalType(T).getUnqualifiedType();
1333
1334 // -- If T is a pointer to U or an array of U, its associated
1335 // namespaces and classes are those associated with U.
1336 //
1337 // We handle this by unwrapping pointer and array types immediately,
1338 // to avoid unnecessary recursion.
1339 while (true) {
1340 if (const PointerType *Ptr = T->getAsPointerType())
1341 T = Ptr->getPointeeType();
1342 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1343 T = Ptr->getElementType();
1344 else
1345 break;
1346 }
1347
1348 // -- If T is a fundamental type, its associated sets of
1349 // namespaces and classes are both empty.
1350 if (T->getAsBuiltinType())
1351 return;
1352
1353 // -- If T is a class type (including unions), its associated
1354 // classes are: the class itself; the class of which it is a
1355 // member, if any; and its direct and indirect base
1356 // classes. Its associated namespaces are the namespaces in
1357 // which its associated classes are defined.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001358 if (const RecordType *ClassType = T->getAsRecordType())
1359 if (CXXRecordDecl *ClassDecl
1360 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1361 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1362 AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001363 AssociatedClasses,
1364 GlobalScope);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001365 return;
1366 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001367
1368 // -- If T is an enumeration type, its associated namespace is
1369 // the namespace in which it is defined. If it is class
1370 // member, its associated class is the member’s class; else
1371 // it has no associated class.
1372 if (const EnumType *EnumT = T->getAsEnumType()) {
1373 EnumDecl *Enum = EnumT->getDecl();
1374
1375 DeclContext *Ctx = Enum->getDeclContext();
1376 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1377 AssociatedClasses.insert(EnclosingClass);
1378
1379 // Add the associated namespace for this class.
1380 while (Ctx->isRecord())
1381 Ctx = Ctx->getParent();
1382 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1383 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001384 else if (Ctx->isTranslationUnit())
1385 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001386
1387 return;
1388 }
1389
1390 // -- If T is a function type, its associated namespaces and
1391 // classes are those associated with the function parameter
1392 // types and those associated with the return type.
1393 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1394 // Return type
1395 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1396 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001397 AssociatedNamespaces, AssociatedClasses,
1398 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001399
Douglas Gregor72564e72009-02-26 23:50:07 +00001400 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001401 if (!Proto)
1402 return;
1403
1404 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001405 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001406 ArgEnd = Proto->arg_type_end();
1407 Arg != ArgEnd; ++Arg)
1408 addAssociatedClassesAndNamespaces(*Arg, Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001409 AssociatedNamespaces, AssociatedClasses,
1410 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001411
1412 return;
1413 }
1414
1415 // -- If T is a pointer to a member function of a class X, its
1416 // associated namespaces and classes are those associated
1417 // with the function parameter types and return type,
1418 // together with those associated with X.
1419 //
1420 // -- If T is a pointer to a data member of class X, its
1421 // associated namespaces and classes are those associated
1422 // with the member type together with those associated with
1423 // X.
1424 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1425 // Handle the type that the pointer to member points to.
1426 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1427 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001428 AssociatedNamespaces, AssociatedClasses,
1429 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001430
1431 // Handle the class type into which this points.
1432 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1433 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1434 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001435 AssociatedNamespaces, AssociatedClasses,
1436 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001437
1438 return;
1439 }
1440
1441 // FIXME: What about block pointers?
1442 // FIXME: What about Objective-C message sends?
1443}
1444
1445/// \brief Find the associated classes and namespaces for
1446/// argument-dependent lookup for a call with the given set of
1447/// arguments.
1448///
1449/// This routine computes the sets of associated classes and associated
1450/// namespaces searched by argument-dependent lookup
1451/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1452void
1453Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1454 AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001455 AssociatedClassSet &AssociatedClasses,
1456 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001457 AssociatedNamespaces.clear();
1458 AssociatedClasses.clear();
1459
1460 // C++ [basic.lookup.koenig]p2:
1461 // For each argument type T in the function call, there is a set
1462 // of zero or more associated namespaces and a set of zero or more
1463 // associated classes to be considered. The sets of namespaces and
1464 // classes is determined entirely by the types of the function
1465 // arguments (and the namespace of any template template
1466 // argument).
1467 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1468 Expr *Arg = Args[ArgIdx];
1469
1470 if (Arg->getType() != Context.OverloadTy) {
1471 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001472 AssociatedNamespaces, AssociatedClasses,
1473 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001474 continue;
1475 }
1476
1477 // [...] In addition, if the argument is the name or address of a
1478 // set of overloaded functions and/or function templates, its
1479 // associated classes and namespaces are the union of those
1480 // associated with each of the members of the set: the namespace
1481 // in which the function or function template is defined and the
1482 // classes and namespaces associated with its (non-dependent)
1483 // parameter types and return type.
1484 DeclRefExpr *DRE = 0;
1485 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1486 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1487 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1488 } else
1489 DRE = dyn_cast<DeclRefExpr>(Arg);
1490 if (!DRE)
1491 continue;
1492
1493 OverloadedFunctionDecl *Ovl
1494 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1495 if (!Ovl)
1496 continue;
1497
1498 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1499 FuncEnd = Ovl->function_end();
1500 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001501 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1502 if (!FDecl)
1503 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001504
1505 // Add the namespace in which this function was defined. Note
1506 // that, if this is a member function, we do *not* consider the
1507 // enclosing namespace of its class.
1508 DeclContext *Ctx = FDecl->getDeclContext();
1509 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1510 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001511 else if (Ctx->isTranslationUnit())
1512 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001513
1514 // Add the classes and namespaces associated with the parameter
1515 // types and return type of this function.
1516 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001517 AssociatedNamespaces, AssociatedClasses,
1518 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001519 }
1520 }
1521}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001522
1523/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1524/// an acceptable non-member overloaded operator for a call whose
1525/// arguments have types T1 (and, if non-empty, T2). This routine
1526/// implements the check in C++ [over.match.oper]p3b2 concerning
1527/// enumeration types.
1528static bool
1529IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1530 QualType T1, QualType T2,
1531 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001532 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1533 return true;
1534
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001535 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1536 return true;
1537
1538 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1539 if (Proto->getNumArgs() < 1)
1540 return false;
1541
1542 if (T1->isEnumeralType()) {
1543 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1544 if (Context.getCanonicalType(T1).getUnqualifiedType()
1545 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1546 return true;
1547 }
1548
1549 if (Proto->getNumArgs() < 2)
1550 return false;
1551
1552 if (!T2.isNull() && T2->isEnumeralType()) {
1553 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1554 if (Context.getCanonicalType(T2).getUnqualifiedType()
1555 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1556 return true;
1557 }
1558
1559 return false;
1560}
1561
Douglas Gregor6e378de2009-04-23 23:18:26 +00001562/// \brief Find the protocol with the given name, if any.
1563ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001564 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregor6e378de2009-04-23 23:18:26 +00001565 return cast_or_null<ObjCProtocolDecl>(D);
1566}
1567
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001568/// \brief Find the Objective-C implementation with the given name, if
1569/// any.
1570ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1571 Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1572 return cast_or_null<ObjCImplementationDecl>(D);
1573}
1574
1575/// \brief Find the Objective-C category implementation with the given
1576/// name, if any.
1577ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1578 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1579 return cast_or_null<ObjCCategoryImplDecl>(D);
1580}
1581
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001582void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1583 QualType T1, QualType T2,
1584 FunctionSet &Functions) {
1585 // C++ [over.match.oper]p3:
1586 // -- The set of non-member candidates is the result of the
1587 // unqualified lookup of operator@ in the context of the
1588 // expression according to the usual rules for name lookup in
1589 // unqualified function calls (3.4.2) except that all member
1590 // functions are ignored. However, if no operand has a class
1591 // type, only those non-member functions in the lookup set
1592 // that have a first parameter of type T1 or “reference to
1593 // (possibly cv-qualified) T1”, when T1 is an enumeration
1594 // type, or (if there is a right operand) a second parameter
1595 // of type T2 or “reference to (possibly cv-qualified) T2”,
1596 // when T2 is an enumeration type, are candidate functions.
1597 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1598 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1599
1600 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1601
1602 if (!Operators)
1603 return;
1604
1605 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1606 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001607 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001608 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1609 Functions.insert(FD); // FIXME: canonical FD
Douglas Gregor364e0212009-06-27 21:05:07 +00001610 } else if (FunctionTemplateDecl *FunTmpl
1611 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1612 // FIXME: friend operators?
1613 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
1614 // later?
1615 if (!FunTmpl->getDeclContext()->isRecord())
1616 Functions.insert(FunTmpl);
1617 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001618 }
1619}
1620
1621void Sema::ArgumentDependentLookup(DeclarationName Name,
1622 Expr **Args, unsigned NumArgs,
1623 FunctionSet &Functions) {
1624 // Find all of the associated namespaces and classes based on the
1625 // arguments we have.
1626 AssociatedNamespaceSet AssociatedNamespaces;
1627 AssociatedClassSet AssociatedClasses;
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001628 bool GlobalScope = false;
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001629 FindAssociatedClassesAndNamespaces(Args, NumArgs,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001630 AssociatedNamespaces, AssociatedClasses,
1631 GlobalScope);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001632
1633 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001634 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1635 // and let Y be the lookup set produced by argument dependent
1636 // lookup (defined as follows). If X contains [...] then Y is
1637 // empty. Otherwise Y is the set of declarations found in the
1638 // namespaces associated with the argument types as described
1639 // below. The set of declarations found by the lookup of the name
1640 // is the union of X and Y.
1641 //
1642 // Here, we compute Y and add its members to the overloaded
1643 // candidate set.
1644 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1645 NSEnd = AssociatedNamespaces.end();
1646 NS != NSEnd; ++NS) {
1647 // When considering an associated namespace, the lookup is the
1648 // same as the lookup performed when the associated namespace is
1649 // used as a qualifier (3.4.3.2) except that:
1650 //
1651 // -- Any using-directives in the associated namespace are
1652 // ignored.
1653 //
1654 // -- FIXME: Any namespace-scope friend functions declared in
1655 // associated classes are visible within their respective
1656 // namespaces even if they are not visible during an ordinary
1657 // lookup (11.4).
1658 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001659 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001660 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*I))
1661 Functions.insert(Func);
1662 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*I))
1663 Functions.insert(FunTmpl);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001664 }
1665 }
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001666
1667 if (GlobalScope) {
1668 DeclContext::lookup_iterator I, E;
1669 for (llvm::tie(I, E)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001670 = Context.getTranslationUnitDecl()->lookup(Name);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001671 I != E; ++I) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001672 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*I))
1673 Functions.insert(Func);
1674 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*I))
1675 Functions.insert(FunTmpl);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001676 }
1677 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001678}