blob: 4d25f5b4804c29fa6ea6b51e8cabf89f5f8efed9 [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();
215 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
216 TagFound = Context.getCanonicalDecl(TD);
217 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000218 } else if (ND->isFunctionOrFunctionTemplate())
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000219 Functions += FoundDecls.insert(ND)? 1 : 0;
220 else
221 FoundDecls.insert(ND);
222 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000223 }
224
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000225 case LResult::FoundOverloaded:
226 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
227 Functions += FoundDecls.insert(*FI)? 1 : 0;
228 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000229 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000230 }
231 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
232 bool Ambiguous = false, NameHidesTags = false;
233
234 if (FoundDecls.size() == 1) {
235 // 1) Exactly one result.
236 } else if (TagNames > 1) {
237 // 2) Multiple tag names (even though they may be hidden by an
238 // object name).
239 Ambiguous = true;
240 } else if (FoundDecls.size() - TagNames == 1) {
241 // 3) Ordinary name hides (optional) tag.
242 NameHidesTags = TagFound;
243 } else if (Functions) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000244 // C++ [basic.lookup].p1:
245 // ... Name lookup may associate more than one declaration with
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000246 // a name if it finds the name to be a function name; the declarations
247 // are said to form a set of overloaded functions (13.1).
248 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000249 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000250 if (!OrdinaryNonFunc) {
251 // 4) Functions hide tag names.
252 NameHidesTags = TagFound;
253 } else {
254 // 5) Functions + ordinary names.
255 Ambiguous = true;
256 }
257 } else {
258 // 6) Multiple non-tag names
259 Ambiguous = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000260 }
261
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000262 if (Ambiguous)
263 return LResult::CreateLookupResult(Context,
264 FoundDecls.begin(), FoundDecls.size());
265 if (NameHidesTags) {
266 // There's only one tag, TagFound. Remove it.
267 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
268 FoundDecls.erase(TagFound);
269 }
270
271 // Return successful name lookup result.
272 return LResult::CreateLookupResult(Context,
273 MaybeConstructOverloadSet(Context,
274 FoundDecls.begin(),
275 FoundDecls.end()));
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000276}
277
278// Retrieve the set of identifier namespaces that correspond to a
279// specific kind of name lookup.
280inline unsigned
281getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
282 bool CPlusPlus) {
283 unsigned IDNS = 0;
284 switch (NameKind) {
285 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000286 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000287 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000288 IDNS = Decl::IDNS_Ordinary;
289 if (CPlusPlus)
290 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
291 break;
292
293 case Sema::LookupTagName:
294 IDNS = Decl::IDNS_Tag;
295 break;
296
297 case Sema::LookupMemberName:
298 IDNS = Decl::IDNS_Member;
299 if (CPlusPlus)
300 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
301 break;
302
303 case Sema::LookupNestedNameSpecifierName:
304 case Sema::LookupNamespaceName:
305 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
306 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000307
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000308 case Sema::LookupObjCProtocolName:
309 IDNS = Decl::IDNS_ObjCProtocol;
310 break;
311
312 case Sema::LookupObjCImplementationName:
313 IDNS = Decl::IDNS_ObjCImplementation;
314 break;
315
316 case Sema::LookupObjCCategoryImplName:
317 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000318 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000319 }
320 return IDNS;
321}
322
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000323Sema::LookupResult
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000324Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor516ff432009-04-24 02:57:34 +0000325 if (ObjCCompatibleAliasDecl *Alias
326 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
327 D = Alias->getClassInterface();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000328 if (UsingDecl *UD = dyn_cast_or_null<UsingDecl>(D))
329 D = UD->getTargetDecl();
330
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
359 Decl *D = *F;
360 if (ObjCCompatibleAliasDecl *Alias
361 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
362 D = Alias->getClassInterface();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000363 if (UsingDecl *UD = dyn_cast_or_null<UsingDecl>(D))
364 D = UD->getTargetDecl();
365
Douglas Gregor69d993a2009-01-17 01:13:24 +0000366 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000367 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000368 Result.Last = 0;
369 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000370}
371
Douglas Gregor69d993a2009-01-17 01:13:24 +0000372Sema::LookupResult
373Sema::LookupResult::CreateLookupResult(ASTContext &Context,
374 DeclContext::lookup_iterator F,
375 DeclContext::lookup_iterator L) {
376 LookupResult Result;
377 Result.Context = &Context;
378
Douglas Gregore53060f2009-06-25 22:08:12 +0000379 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000380 DeclContext::lookup_iterator Next = F;
381 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000382 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000383 Result.StoredKind = OverloadedDeclFromDeclContext;
384 Result.First = reinterpret_cast<uintptr_t>(F);
385 Result.Last = reinterpret_cast<uintptr_t>(L);
386 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000387 }
388 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000389
390 Decl *D = *F;
391 if (ObjCCompatibleAliasDecl *Alias
392 = dyn_cast_or_null<ObjCCompatibleAliasDecl>(D))
393 D = Alias->getClassInterface();
Douglas Gregor7176fff2009-01-15 00:26:24 +0000394
Douglas Gregor69d993a2009-01-17 01:13:24 +0000395 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000396 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000397 Result.Last = 0;
398 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000399}
400
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000401/// @brief Determine the result of name lookup.
402Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
403 switch (StoredKind) {
404 case SingleDecl:
405 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
406
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000407 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000408 case OverloadedDeclFromIdResolver:
409 case OverloadedDeclFromDeclContext:
410 return FoundOverloaded;
411
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000412 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000413 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000414
415 case AmbiguousLookupStoresDecls:
416 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000417 }
418
Douglas Gregor7176fff2009-01-15 00:26:24 +0000419 // We can't ever get here.
420 return NotFound;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000421}
422
423/// @brief Converts the result of name lookup into a single (possible
424/// NULL) pointer to a declaration.
425///
426/// The resulting declaration will either be the declaration we found
427/// (if only a single declaration was found), an
428/// OverloadedFunctionDecl (if an overloaded function was found), or
429/// NULL (if no declaration was found). This conversion must not be
430/// used anywhere where name lookup could result in an ambiguity.
431///
432/// The OverloadedFunctionDecl conversion is meant as a stop-gap
433/// solution, since it causes the OverloadedFunctionDecl to be
434/// leaked. FIXME: Eventually, there will be a better way to iterate
435/// over the set of overloaded functions returned by name lookup.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000436NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000437 switch (StoredKind) {
438 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000439 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000440
441 case OverloadedDeclFromIdResolver:
442 return MaybeConstructOverloadSet(*Context,
443 IdentifierResolver::iterator::getFromOpaqueValue(First),
444 IdentifierResolver::iterator::getFromOpaqueValue(Last));
445
446 case OverloadedDeclFromDeclContext:
447 return MaybeConstructOverloadSet(*Context,
448 reinterpret_cast<DeclContext::lookup_iterator>(First),
449 reinterpret_cast<DeclContext::lookup_iterator>(Last));
450
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000451 case OverloadedDeclSingleDecl:
452 return reinterpret_cast<OverloadedFunctionDecl*>(First);
453
454 case AmbiguousLookupStoresDecls:
455 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000456 assert(false &&
457 "Name lookup returned an ambiguity that could not be handled");
458 break;
459 }
460
461 return 0;
462}
463
Douglas Gregor7176fff2009-01-15 00:26:24 +0000464/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000465/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000466BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000467 if (StoredKind == AmbiguousLookupStoresBasePaths)
468 return reinterpret_cast<BasePaths *>(First);
469 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000470}
471
Douglas Gregord8635172009-02-02 21:35:47 +0000472Sema::LookupResult::iterator::reference
473Sema::LookupResult::iterator::operator*() const {
474 switch (Result->StoredKind) {
475 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000476 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000477
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000478 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000479 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000480
Douglas Gregord8635172009-02-02 21:35:47 +0000481 case OverloadedDeclFromIdResolver:
482 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
483
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000484 case AmbiguousLookupStoresBasePaths:
Douglas Gregor31a19b62009-04-01 21:51:26 +0000485 if (Result->Last)
486 return *reinterpret_cast<NamedDecl**>(Current);
487
488 // Fall through to handle the DeclContext::lookup_iterator we're
489 // storing.
490
491 case OverloadedDeclFromDeclContext:
492 case AmbiguousLookupStoresDecls:
493 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000494 }
495
496 return 0;
497}
498
499Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
500 switch (Result->StoredKind) {
501 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000502 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000503 break;
504
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000505 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000506 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000507 ++I;
508 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000509 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000510 }
511
Douglas Gregord8635172009-02-02 21:35:47 +0000512 case OverloadedDeclFromIdResolver: {
513 IdentifierResolver::iterator I
514 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
515 ++I;
516 Current = I.getAsOpaqueValue();
517 break;
518 }
519
Douglas Gregor31a19b62009-04-01 21:51:26 +0000520 case AmbiguousLookupStoresBasePaths:
521 if (Result->Last) {
522 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
523 ++I;
524 Current = reinterpret_cast<uintptr_t>(I);
525 break;
526 }
527 // Fall through to handle the DeclContext::lookup_iterator we're
528 // storing.
529
530 case OverloadedDeclFromDeclContext:
531 case AmbiguousLookupStoresDecls: {
Douglas Gregord8635172009-02-02 21:35:47 +0000532 DeclContext::lookup_iterator I
533 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
534 ++I;
535 Current = reinterpret_cast<uintptr_t>(I);
536 break;
537 }
Douglas Gregord8635172009-02-02 21:35:47 +0000538 }
539
540 return *this;
541}
542
543Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000544 switch (StoredKind) {
545 case SingleDecl:
546 case OverloadedDeclFromIdResolver:
547 case OverloadedDeclFromDeclContext:
548 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000549 return iterator(this, First);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000550
551 case OverloadedDeclSingleDecl: {
552 OverloadedFunctionDecl * Ovl =
553 reinterpret_cast<OverloadedFunctionDecl*>(First);
554 return iterator(this,
555 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
556 }
557
558 case AmbiguousLookupStoresBasePaths:
559 if (Last)
560 return iterator(this,
561 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
562 else
563 return iterator(this,
564 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
565 }
566
567 // Required to suppress GCC warning.
568 return iterator();
Douglas Gregord8635172009-02-02 21:35:47 +0000569}
570
571Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000572 switch (StoredKind) {
573 case SingleDecl:
574 case OverloadedDeclFromIdResolver:
575 case OverloadedDeclFromDeclContext:
576 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000577 return iterator(this, Last);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000578
579 case OverloadedDeclSingleDecl: {
580 OverloadedFunctionDecl * Ovl =
581 reinterpret_cast<OverloadedFunctionDecl*>(First);
582 return iterator(this,
583 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
584 }
585
586 case AmbiguousLookupStoresBasePaths:
587 if (Last)
588 return iterator(this,
589 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
590 else
591 return iterator(this, reinterpret_cast<uintptr_t>(
592 getBasePaths()->front().Decls.second));
593 }
594
595 // Required to suppress GCC warning.
596 return iterator();
597}
598
599void Sema::LookupResult::Destroy() {
600 if (BasePaths *Paths = getBasePaths())
601 delete Paths;
602 else if (getKind() == AmbiguousReference)
603 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregord8635172009-02-02 21:35:47 +0000604}
605
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000606static void
607CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
608 DeclarationName Name, Sema::LookupNameKind NameKind,
609 unsigned IDNS, LookupResultsTy &Results,
610 UsingDirectivesTy *UDirs = 0) {
611
612 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
613
614 // Perform qualified name lookup into the LookupCtx.
615 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000616 for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000617 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
618 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
619 break;
620 }
621
622 if (UDirs) {
623 // For each UsingDirectiveDecl, which common ancestor is equal
624 // to NS, we preform qualified name lookup into namespace nominated by it.
625 UsingDirectivesTy::const_iterator UI, UEnd;
626 llvm::tie(UI, UEnd) =
627 std::equal_range(UDirs->begin(), UDirs->end(), NS,
628 UsingDirAncestorCompare());
629
630 for (; UI != UEnd; ++UI)
631 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
632 Name, NameKind, IDNS, Results);
633 }
634}
635
636static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000637 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000638 return Ctx->isFileContext();
639 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000640}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000641
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000642std::pair<bool, Sema::LookupResult>
643Sema::CppLookupName(Scope *S, DeclarationName Name,
644 LookupNameKind NameKind, bool RedeclarationOnly) {
645 assert(getLangOptions().CPlusPlus &&
646 "Can perform only C++ lookup");
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000647 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000648 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000649 Scope *Initial = S;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000650 DeclContext *OutOfLineCtx = 0;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000651 IdentifierResolver::iterator
652 I = IdResolver.begin(Name),
653 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000654
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000655 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000656 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000657 // ...During unqualified name lookup (3.4.1), the names appear as if
658 // they were declared in the nearest enclosing namespace which contains
659 // both the using-directive and the nominated namespace.
660 // [Note: in this context, “contains” means “contains directly or
661 // indirectly”.
662 //
663 // For example:
664 // namespace A { int i; }
665 // void foo() {
666 // int i;
667 // {
668 // using namespace A;
669 // ++i; // finds local 'i', A::i appears at global scope
670 // }
671 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000672 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000673 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000674 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000675 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000676 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
677 // We found something. Look for anything else in our scope
678 // with this same name and in an acceptable identifier
679 // namespace, so that we can construct an overload set if we
680 // need to.
681 IdentifierResolver::iterator LastI = I;
682 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000683 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000684 break;
685 }
686 LookupResult Result =
687 LookupResult::CreateLookupResult(Context, I, LastI);
688 return std::make_pair(true, Result);
689 }
690 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000691 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
692 LookupResult R;
693 // Perform member lookup into struct.
Mike Stump390b4cc2009-05-16 07:39:55 +0000694 // FIXME: In some cases, we know that every name that could be found by
695 // this qualified name lookup will also be on the identifier chain. For
696 // example, inside a class without any base classes, we never need to
697 // perform qualified lookup because all of the members are on top of the
698 // identifier chain.
Douglas Gregor551f48c2009-03-27 04:21:56 +0000699 if (isa<RecordDecl>(Ctx)) {
700 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000701 if (R)
Douglas Gregor551f48c2009-03-27 04:21:56 +0000702 return std::make_pair(true, R);
703 }
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000704 if (Ctx->getParent() != Ctx->getLexicalParent()
705 || isa<CXXMethodDecl>(Ctx)) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000706 // It is out of line defined C++ method or struct, we continue
707 // doing name lookup in parent context. Once we will find namespace
708 // or translation-unit we save it for possible checking
709 // using-directives later.
710 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
711 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregor551f48c2009-03-27 04:21:56 +0000712 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000713 if (R)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000714 return std::make_pair(true, R);
715 }
716 }
717 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000718 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000719
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000720 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000721 // nominated namespaces by those using-directives.
Mike Stump390b4cc2009-05-16 07:39:55 +0000722 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
723 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
724 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000725 UsingDirectivesTy UDirs;
726 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000727 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregor6ab35242009-04-09 21:40:53 +0000728 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000729
730 // Sort heapified UsingDirectiveDecls.
Douglas Gregorb738e082009-05-18 22:06:54 +0000731 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000732
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000733 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000734 // Unqualified name lookup in C++ requires looking into scopes
735 // that aren't strictly lexical, and therefore we walk through the
736 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000737
738 LookupResultsTy LookupResults;
Sebastian Redl22460502009-02-07 00:15:38 +0000739 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000740 "We should have been looking only at file context here already.");
741 bool LookedInCtx = false;
742 LookupResult Result;
743 while (OutOfLineCtx &&
744 OutOfLineCtx != S->getEntity() &&
745 OutOfLineCtx->isNamespace()) {
746 LookedInCtx = true;
747
748 // Look into context considering using-directives.
749 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
750 LookupResults, &UDirs);
751
752 if ((Result = MergeLookupResults(Context, LookupResults)) ||
753 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
754 return std::make_pair(true, Result);
755
756 OutOfLineCtx = OutOfLineCtx->getParent();
757 }
758
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000759 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000760 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
761 assert(Ctx && Ctx->isFileContext() &&
762 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000763
764 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000765 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000766 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
767 // We found something. Look for anything else in our scope
768 // with this same name and in an acceptable identifier
769 // namespace, so that we can construct an overload set if we
770 // need to.
771 IdentifierResolver::iterator LastI = I;
772 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000773 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000774 break;
775 }
776
777 // We store name lookup result, and continue trying to look into
778 // associated context, and maybe namespaces nominated by
779 // using-directives.
780 LookupResults.push_back(
781 LookupResult::CreateLookupResult(Context, I, LastI));
782 break;
783 }
784 }
785
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000786 LookedInCtx = true;
787 // Look into context considering using-directives.
788 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
789 LookupResults, &UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000790
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000791 if ((Result = MergeLookupResults(Context, LookupResults)) ||
792 (RedeclarationOnly && !Ctx->isTransparentContext()))
793 return std::make_pair(true, Result);
794 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000795
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000796 if (!(LookedInCtx || LookupResults.empty())) {
797 // We didn't Performed lookup in Scope entity, so we return
798 // result form IdentifierResolver.
799 assert((LookupResults.size() == 1) && "Wrong size!");
800 return std::make_pair(true, LookupResults.front());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000801 }
802 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000803}
804
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000805/// @brief Perform unqualified name lookup starting from a given
806/// scope.
807///
808/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
809/// used to find names within the current scope. For example, 'x' in
810/// @code
811/// int x;
812/// int f() {
813/// return x; // unqualified name look finds 'x' in the global scope
814/// }
815/// @endcode
816///
817/// Different lookup criteria can find different names. For example, a
818/// particular scope can have both a struct and a function of the same
819/// name, and each can be found by certain lookup criteria. For more
820/// information about lookup criteria, see the documentation for the
821/// class LookupCriteria.
822///
823/// @param S The scope from which unqualified name lookup will
824/// begin. If the lookup criteria permits, name lookup may also search
825/// in the parent scopes.
826///
827/// @param Name The name of the entity that we are searching for.
828///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000829/// @param Loc If provided, the source location where we're performing
830/// name lookup. At present, this is only used to produce diagnostics when
831/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000832///
833/// @returns The result of name lookup, which includes zero or more
834/// declarations and possibly additional information used to diagnose
835/// ambiguities.
836Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000837Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000838 bool RedeclarationOnly, bool AllowBuiltinCreation,
839 SourceLocation Loc) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000840 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000841
842 if (!getLangOptions().CPlusPlus) {
843 // Unqualified name lookup in C/Objective-C is purely lexical, so
844 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000845 unsigned IDNS = 0;
846 switch (NameKind) {
847 case Sema::LookupOrdinaryName:
848 IDNS = Decl::IDNS_Ordinary;
849 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000850
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000851 case Sema::LookupTagName:
852 IDNS = Decl::IDNS_Tag;
853 break;
854
855 case Sema::LookupMemberName:
856 IDNS = Decl::IDNS_Member;
857 break;
858
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000859 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000860 case Sema::LookupNestedNameSpecifierName:
861 case Sema::LookupNamespaceName:
862 assert(false && "C does not perform these kinds of name lookup");
863 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000864
865 case Sema::LookupRedeclarationWithLinkage:
866 // Find the nearest non-transparent declaration scope.
867 while (!(S->getFlags() & Scope::DeclScope) ||
868 (S->getEntity() &&
869 static_cast<DeclContext *>(S->getEntity())
870 ->isTransparentContext()))
871 S = S->getParent();
872 IDNS = Decl::IDNS_Ordinary;
873 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000874
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000875 case Sema::LookupObjCProtocolName:
876 IDNS = Decl::IDNS_ObjCProtocol;
877 break;
878
879 case Sema::LookupObjCImplementationName:
880 IDNS = Decl::IDNS_ObjCImplementation;
881 break;
882
883 case Sema::LookupObjCCategoryImplName:
884 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000885 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000886 }
887
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000888 // Scan up the scope chain looking for a decl that matches this
889 // identifier that is in the appropriate namespace. This search
890 // should not take long, as shadowing of names is uncommon, and
891 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000892 bool LeftStartingScope = false;
893
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000894 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
895 IEnd = IdResolver.end();
896 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000897 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000898 if (NameKind == LookupRedeclarationWithLinkage) {
899 // Determine whether this (or a previous) declaration is
900 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000901 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000902 LeftStartingScope = true;
903
904 // If we found something outside of our starting scope that
905 // does not have linkage, skip it.
906 if (LeftStartingScope && !((*I)->hasLinkage()))
907 continue;
908 }
909
Douglas Gregor68584ed2009-06-18 16:11:24 +0000910 if ((*I)->getAttr<OverloadableAttr>(Context)) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000911 // If this declaration has the "overloadable" attribute, we
912 // might have a set of overloaded functions.
913
914 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000915 while (!(S->getFlags() & Scope::DeclScope) ||
916 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000917 S = S->getParent();
918
919 // Find the last declaration in this scope (with the same
920 // name, naturally).
921 IdentifierResolver::iterator LastI = I;
922 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000923 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000924 break;
925 }
926
927 return LookupResult::CreateLookupResult(Context, I, LastI);
928 }
929
930 // We have a single lookup result.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000931 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000932 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000933 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000934 // Perform C++ unqualified name lookup.
935 std::pair<bool, LookupResult> MaybeResult =
936 CppLookupName(S, Name, NameKind, RedeclarationOnly);
937 if (MaybeResult.first)
938 return MaybeResult.second;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000939 }
940
941 // If we didn't find a use of this identifier, and if the identifier
942 // corresponds to a compiler builtin, create the decl object for the builtin
943 // now, injecting it into translation unit scope, and return it.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000944 if (NameKind == LookupOrdinaryName ||
945 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000946 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000947 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000948 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000949 if (unsigned BuiltinID = II->getBuiltinID()) {
950 // In C++, we don't have any predefined library functions like
951 // 'malloc'. Instead, we'll just error.
952 if (getLangOptions().CPlusPlus &&
953 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
954 return LookupResult::CreateLookupResult(Context, 0);
955
Douglas Gregor69d993a2009-01-17 01:13:24 +0000956 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000957 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000958 S, RedeclarationOnly, Loc));
959 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000960 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000961 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000962 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000963}
964
965/// @brief Perform qualified name lookup into a given context.
966///
967/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
968/// names when the context of those names is explicit specified, e.g.,
969/// "std::vector" or "x->member".
970///
971/// Different lookup criteria can find different names. For example, a
972/// particular scope can have both a struct and a function of the same
973/// name, and each can be found by certain lookup criteria. For more
974/// information about lookup criteria, see the documentation for the
975/// class LookupCriteria.
976///
977/// @param LookupCtx The context in which qualified name lookup will
978/// search. If the lookup criteria permits, name lookup may also search
979/// in the parent contexts or (for C++ classes) base classes.
980///
981/// @param Name The name of the entity that we are searching for.
982///
983/// @param Criteria The criteria that this routine will use to
984/// determine which names are visible and which names will be
985/// found. Note that name lookup will find a name that is visible by
986/// the given criteria, but the entity itself may not be semantically
987/// correct or even the kind of entity expected based on the
988/// lookup. For example, searching for a nested-name-specifier name
989/// might result in an EnumDecl, which is visible but is not permitted
990/// as a nested-name-specifier in C++03.
991///
992/// @returns The result of name lookup, which includes zero or more
993/// declarations and possibly additional information used to diagnose
994/// ambiguities.
995Sema::LookupResult
996Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000997 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000998 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
999
Douglas Gregor69d993a2009-01-17 01:13:24 +00001000 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001001
1002 // If we're performing qualified name lookup (e.g., lookup into a
1003 // struct), find fields as part of ordinary name lookup.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001004 unsigned IDNS
1005 = getIdentifierNamespacesFromLookupNameKind(NameKind,
1006 getLangOptions().CPlusPlus);
1007 if (NameKind == LookupOrdinaryName)
1008 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001009
1010 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001011 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001012 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001013 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001014 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001015
Douglas Gregor7176fff2009-01-15 00:26:24 +00001016 // If this isn't a C++ class or we aren't allowed to look into base
1017 // classes, we're done.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001018 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001019 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001020
1021 // Perform lookup into our base classes.
1022 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001023 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +00001024
1025 // Look for this member in our base classes
1026 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001027 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001028 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001029
1030 // C++ [class.member.lookup]p2:
1031 // [...] If the resulting set of declarations are not all from
1032 // sub-objects of the same type, or the set has a nonstatic member
1033 // and includes members from distinct sub-objects, there is an
1034 // ambiguity and the program is ill-formed. Otherwise that set is
1035 // the result of the lookup.
1036 // FIXME: support using declarations!
1037 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001038 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001039 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1040 Path != PathEnd; ++Path) {
1041 const BasePathElement &PathElement = Path->back();
1042
1043 // Determine whether we're looking at a distinct sub-object or not.
1044 if (SubobjectType.isNull()) {
1045 // This is the first subobject we've looked at. Record it's type.
1046 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1047 SubobjectNumber = PathElement.SubobjectNumber;
1048 } else if (SubobjectType
1049 != Context.getCanonicalType(PathElement.Base->getType())) {
1050 // We found members of the given name in two subobjects of
1051 // different types. This lookup is ambiguous.
1052 BasePaths *PathsOnHeap = new BasePaths;
1053 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001054 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001055 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1056 // We have a different subobject of the same type.
1057
1058 // C++ [class.member.lookup]p5:
1059 // A static member, a nested type or an enumerator defined in
1060 // a base class T can unambiguously be found even if an object
1061 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001062 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001063 if (isa<VarDecl>(FirstDecl) ||
1064 isa<TypeDecl>(FirstDecl) ||
1065 isa<EnumConstantDecl>(FirstDecl))
1066 continue;
1067
1068 if (isa<CXXMethodDecl>(FirstDecl)) {
1069 // Determine whether all of the methods are static.
1070 bool AllMethodsAreStatic = true;
1071 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1072 Func != Path->Decls.second; ++Func) {
1073 if (!isa<CXXMethodDecl>(*Func)) {
1074 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1075 break;
1076 }
1077
1078 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1079 AllMethodsAreStatic = false;
1080 break;
1081 }
1082 }
1083
1084 if (AllMethodsAreStatic)
1085 continue;
1086 }
1087
1088 // We have found a nonstatic member name in multiple, distinct
1089 // subobjects. Name lookup is ambiguous.
1090 BasePaths *PathsOnHeap = new BasePaths;
1091 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001092 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001093 }
1094 }
1095
1096 // Lookup in a base class succeeded; return these results.
1097
1098 // If we found a function declaration, return an overload set.
Douglas Gregore53060f2009-06-25 22:08:12 +00001099 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
Douglas Gregor69d993a2009-01-17 01:13:24 +00001100 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-01-15 00:26:24 +00001101 Paths.front().Decls.first, Paths.front().Decls.second);
1102
1103 // We found a non-function declaration; return a single declaration.
Douglas Gregor69d993a2009-01-17 01:13:24 +00001104 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001105}
1106
1107/// @brief Performs name lookup for a name that was parsed in the
1108/// source code, and may contain a C++ scope specifier.
1109///
1110/// This routine is a convenience routine meant to be called from
1111/// contexts that receive a name and an optional C++ scope specifier
1112/// (e.g., "N::M::x"). It will then perform either qualified or
1113/// unqualified name lookup (with LookupQualifiedName or LookupName,
1114/// respectively) on the given name and return those results.
1115///
1116/// @param S The scope from which unqualified name lookup will
1117/// begin.
1118///
1119/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1120///
1121/// @param Name The name of the entity that name lookup will
1122/// search for.
1123///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001124/// @param Loc If provided, the source location where we're performing
1125/// name lookup. At present, this is only used to produce diagnostics when
1126/// C library functions (like "malloc") are implicitly declared.
1127///
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001128/// @returns The result of qualified or unqualified name lookup.
1129Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001130Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1131 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001132 bool RedeclarationOnly, bool AllowBuiltinCreation,
1133 SourceLocation Loc) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00001134 if (SS && (SS->isSet() || SS->isInvalid())) {
1135 // If the scope specifier is invalid, don't even look for
1136 // anything.
1137 if (SS->isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001138 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001139
Douglas Gregor42af25f2009-05-11 19:58:34 +00001140 assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1141
1142 if (isDependentScopeSpecifier(*SS)) {
1143 // Determine whether we are looking into the current
1144 // instantiation.
1145 NestedNameSpecifier *NNS
1146 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1147 CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1148 assert(Current && "Bad dependent scope specifier");
1149
1150 // We nested name specifier refers to the current instantiation,
1151 // so now we will look for a member of the current instantiation
1152 // (C++0x [temp.dep.type]).
1153 unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1154 DeclContext::lookup_iterator I, E;
1155 for (llvm::tie(I, E) = Current->lookup(Context, Name); I != E; ++I)
1156 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1157 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001158 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001159
1160 if (RequireCompleteDeclContext(*SS))
1161 return LookupResult::CreateLookupResult(Context, 0);
1162
1163 return LookupQualifiedName(computeDeclContext(*SS),
1164 Name, NameKind, RedeclarationOnly);
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001165 }
1166
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001167 LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly,
1168 AllowBuiltinCreation, Loc));
1169
1170 return(result);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001171}
1172
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001173
Douglas Gregor7176fff2009-01-15 00:26:24 +00001174/// @brief Produce a diagnostic describing the ambiguity that resulted
1175/// from name lookup.
1176///
1177/// @param Result The ambiguous name lookup result.
1178///
1179/// @param Name The name of the entity that name lookup was
1180/// searching for.
1181///
1182/// @param NameLoc The location of the name within the source code.
1183///
1184/// @param LookupRange A source range that provides more
1185/// source-location information concerning the lookup itself. For
1186/// example, this range might highlight a nested-name-specifier that
1187/// precedes the name.
1188///
1189/// @returns true
1190bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1191 SourceLocation NameLoc,
1192 SourceRange LookupRange) {
1193 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1194
Douglas Gregor31a19b62009-04-01 21:51:26 +00001195 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001196 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1197 QualType SubobjectType = Paths->front().back().Base->getType();
1198 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1199 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1200 << LookupRange;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001201
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001202 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregor31a19b62009-04-01 21:51:26 +00001203 while (isa<CXXMethodDecl>(*Found) &&
1204 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001205 ++Found;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001206
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001207 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1208
Douglas Gregor31a19b62009-04-01 21:51:26 +00001209 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001210 return true;
1211 }
1212
1213 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1214 "Unhandled form of name lookup ambiguity");
1215
1216 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1217 << Name << LookupRange;
1218
1219 std::set<Decl *> DeclsPrinted;
1220 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1221 Path != PathEnd; ++Path) {
1222 Decl *D = *Path->Decls.first;
1223 if (DeclsPrinted.insert(D).second)
1224 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1225 }
1226
Douglas Gregor31a19b62009-04-01 21:51:26 +00001227 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001228 return true;
1229 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001230 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1231
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001232 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregor31a19b62009-04-01 21:51:26 +00001233 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001234
Chris Lattner48458d22009-02-03 21:29:32 +00001235 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001236 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001237
Douglas Gregor31a19b62009-04-01 21:51:26 +00001238 Result.Destroy();
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001239 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001240 }
1241
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001242 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001243
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001244 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001245 return true;
1246}
Douglas Gregorfa047642009-02-04 00:32:51 +00001247
1248// \brief Add the associated classes and namespaces for
1249// argument-dependent lookup with an argument of class type
1250// (C++ [basic.lookup.koenig]p2).
1251static void
1252addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1253 ASTContext &Context,
1254 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001255 Sema::AssociatedClassSet &AssociatedClasses,
1256 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001257 // C++ [basic.lookup.koenig]p2:
1258 // [...]
1259 // -- If T is a class type (including unions), its associated
1260 // classes are: the class itself; the class of which it is a
1261 // member, if any; and its direct and indirect base
1262 // classes. Its associated namespaces are the namespaces in
1263 // which its associated classes are defined.
1264
1265 // Add the class of which it is a member, if any.
1266 DeclContext *Ctx = Class->getDeclContext();
1267 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1268 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001269 // Add the associated namespace for this class.
1270 while (Ctx->isRecord())
1271 Ctx = Ctx->getParent();
1272 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1273 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001274 else if (Ctx->isTranslationUnit())
1275 GlobalScope = true;
1276
Douglas Gregorfa047642009-02-04 00:32:51 +00001277 // Add the class itself. If we've already seen this class, we don't
1278 // need to visit base classes.
1279 if (!AssociatedClasses.insert(Class))
1280 return;
1281
1282 // FIXME: Handle class template specializations
1283
1284 // Add direct and indirect base classes along with their associated
1285 // namespaces.
1286 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1287 Bases.push_back(Class);
1288 while (!Bases.empty()) {
1289 // Pop this class off the stack.
1290 Class = Bases.back();
1291 Bases.pop_back();
1292
1293 // Visit the base classes.
1294 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1295 BaseEnd = Class->bases_end();
1296 Base != BaseEnd; ++Base) {
1297 const RecordType *BaseType = Base->getType()->getAsRecordType();
1298 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1299 if (AssociatedClasses.insert(BaseDecl)) {
1300 // Find the associated namespace for this base class.
1301 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1302 while (BaseCtx->isRecord())
1303 BaseCtx = BaseCtx->getParent();
1304 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1305 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001306 else if (BaseCtx->isTranslationUnit())
1307 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001308
1309 // Make sure we visit the bases of this base class.
1310 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1311 Bases.push_back(BaseDecl);
1312 }
1313 }
1314 }
1315}
1316
1317// \brief Add the associated classes and namespaces for
1318// argument-dependent lookup with an argument of type T
1319// (C++ [basic.lookup.koenig]p2).
1320static void
1321addAssociatedClassesAndNamespaces(QualType T,
1322 ASTContext &Context,
1323 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001324 Sema::AssociatedClassSet &AssociatedClasses,
1325 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001326 // C++ [basic.lookup.koenig]p2:
1327 //
1328 // For each argument type T in the function call, there is a set
1329 // of zero or more associated namespaces and a set of zero or more
1330 // associated classes to be considered. The sets of namespaces and
1331 // classes is determined entirely by the types of the function
1332 // arguments (and the namespace of any template template
1333 // argument). Typedef names and using-declarations used to specify
1334 // the types do not contribute to this set. The sets of namespaces
1335 // and classes are determined in the following way:
1336 T = Context.getCanonicalType(T).getUnqualifiedType();
1337
1338 // -- If T is a pointer to U or an array of U, its associated
1339 // namespaces and classes are those associated with U.
1340 //
1341 // We handle this by unwrapping pointer and array types immediately,
1342 // to avoid unnecessary recursion.
1343 while (true) {
1344 if (const PointerType *Ptr = T->getAsPointerType())
1345 T = Ptr->getPointeeType();
1346 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1347 T = Ptr->getElementType();
1348 else
1349 break;
1350 }
1351
1352 // -- If T is a fundamental type, its associated sets of
1353 // namespaces and classes are both empty.
1354 if (T->getAsBuiltinType())
1355 return;
1356
1357 // -- If T is a class type (including unions), its associated
1358 // classes are: the class itself; the class of which it is a
1359 // member, if any; and its direct and indirect base
1360 // classes. Its associated namespaces are the namespaces in
1361 // which its associated classes are defined.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001362 if (const RecordType *ClassType = T->getAsRecordType())
1363 if (CXXRecordDecl *ClassDecl
1364 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1365 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1366 AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001367 AssociatedClasses,
1368 GlobalScope);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001369 return;
1370 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001371
1372 // -- If T is an enumeration type, its associated namespace is
1373 // the namespace in which it is defined. If it is class
1374 // member, its associated class is the member’s class; else
1375 // it has no associated class.
1376 if (const EnumType *EnumT = T->getAsEnumType()) {
1377 EnumDecl *Enum = EnumT->getDecl();
1378
1379 DeclContext *Ctx = Enum->getDeclContext();
1380 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1381 AssociatedClasses.insert(EnclosingClass);
1382
1383 // Add the associated namespace for this class.
1384 while (Ctx->isRecord())
1385 Ctx = Ctx->getParent();
1386 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1387 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001388 else if (Ctx->isTranslationUnit())
1389 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001390
1391 return;
1392 }
1393
1394 // -- If T is a function type, its associated namespaces and
1395 // classes are those associated with the function parameter
1396 // types and those associated with the return type.
1397 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1398 // Return type
1399 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1400 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001401 AssociatedNamespaces, AssociatedClasses,
1402 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001403
Douglas Gregor72564e72009-02-26 23:50:07 +00001404 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001405 if (!Proto)
1406 return;
1407
1408 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001409 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001410 ArgEnd = Proto->arg_type_end();
1411 Arg != ArgEnd; ++Arg)
1412 addAssociatedClassesAndNamespaces(*Arg, Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001413 AssociatedNamespaces, AssociatedClasses,
1414 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001415
1416 return;
1417 }
1418
1419 // -- If T is a pointer to a member function of a class X, its
1420 // associated namespaces and classes are those associated
1421 // with the function parameter types and return type,
1422 // together with those associated with X.
1423 //
1424 // -- If T is a pointer to a data member of class X, its
1425 // associated namespaces and classes are those associated
1426 // with the member type together with those associated with
1427 // X.
1428 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1429 // Handle the type that the pointer to member points to.
1430 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1431 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001432 AssociatedNamespaces, AssociatedClasses,
1433 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001434
1435 // Handle the class type into which this points.
1436 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1437 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1438 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001439 AssociatedNamespaces, AssociatedClasses,
1440 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001441
1442 return;
1443 }
1444
1445 // FIXME: What about block pointers?
1446 // FIXME: What about Objective-C message sends?
1447}
1448
1449/// \brief Find the associated classes and namespaces for
1450/// argument-dependent lookup for a call with the given set of
1451/// arguments.
1452///
1453/// This routine computes the sets of associated classes and associated
1454/// namespaces searched by argument-dependent lookup
1455/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1456void
1457Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1458 AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001459 AssociatedClassSet &AssociatedClasses,
1460 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001461 AssociatedNamespaces.clear();
1462 AssociatedClasses.clear();
1463
1464 // C++ [basic.lookup.koenig]p2:
1465 // For each argument type T in the function call, there is a set
1466 // of zero or more associated namespaces and a set of zero or more
1467 // associated classes to be considered. The sets of namespaces and
1468 // classes is determined entirely by the types of the function
1469 // arguments (and the namespace of any template template
1470 // argument).
1471 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1472 Expr *Arg = Args[ArgIdx];
1473
1474 if (Arg->getType() != Context.OverloadTy) {
1475 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001476 AssociatedNamespaces, AssociatedClasses,
1477 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001478 continue;
1479 }
1480
1481 // [...] In addition, if the argument is the name or address of a
1482 // set of overloaded functions and/or function templates, its
1483 // associated classes and namespaces are the union of those
1484 // associated with each of the members of the set: the namespace
1485 // in which the function or function template is defined and the
1486 // classes and namespaces associated with its (non-dependent)
1487 // parameter types and return type.
1488 DeclRefExpr *DRE = 0;
1489 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1490 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1491 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1492 } else
1493 DRE = dyn_cast<DeclRefExpr>(Arg);
1494 if (!DRE)
1495 continue;
1496
1497 OverloadedFunctionDecl *Ovl
1498 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1499 if (!Ovl)
1500 continue;
1501
1502 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1503 FuncEnd = Ovl->function_end();
1504 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001505 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1506 if (!FDecl)
1507 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001508
1509 // Add the namespace in which this function was defined. Note
1510 // that, if this is a member function, we do *not* consider the
1511 // enclosing namespace of its class.
1512 DeclContext *Ctx = FDecl->getDeclContext();
1513 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1514 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001515 else if (Ctx->isTranslationUnit())
1516 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001517
1518 // Add the classes and namespaces associated with the parameter
1519 // types and return type of this function.
1520 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001521 AssociatedNamespaces, AssociatedClasses,
1522 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001523 }
1524 }
1525}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001526
1527/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1528/// an acceptable non-member overloaded operator for a call whose
1529/// arguments have types T1 (and, if non-empty, T2). This routine
1530/// implements the check in C++ [over.match.oper]p3b2 concerning
1531/// enumeration types.
1532static bool
1533IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1534 QualType T1, QualType T2,
1535 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001536 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1537 return true;
1538
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001539 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1540 return true;
1541
1542 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1543 if (Proto->getNumArgs() < 1)
1544 return false;
1545
1546 if (T1->isEnumeralType()) {
1547 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1548 if (Context.getCanonicalType(T1).getUnqualifiedType()
1549 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1550 return true;
1551 }
1552
1553 if (Proto->getNumArgs() < 2)
1554 return false;
1555
1556 if (!T2.isNull() && T2->isEnumeralType()) {
1557 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1558 if (Context.getCanonicalType(T2).getUnqualifiedType()
1559 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1560 return true;
1561 }
1562
1563 return false;
1564}
1565
Douglas Gregor6e378de2009-04-23 23:18:26 +00001566/// \brief Find the protocol with the given name, if any.
1567ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001568 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregor6e378de2009-04-23 23:18:26 +00001569 return cast_or_null<ObjCProtocolDecl>(D);
1570}
1571
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001572/// \brief Find the Objective-C implementation with the given name, if
1573/// any.
1574ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1575 Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1576 return cast_or_null<ObjCImplementationDecl>(D);
1577}
1578
1579/// \brief Find the Objective-C category implementation with the given
1580/// name, if any.
1581ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1582 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1583 return cast_or_null<ObjCCategoryImplDecl>(D);
1584}
1585
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001586void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1587 QualType T1, QualType T2,
1588 FunctionSet &Functions) {
1589 // C++ [over.match.oper]p3:
1590 // -- The set of non-member candidates is the result of the
1591 // unqualified lookup of operator@ in the context of the
1592 // expression according to the usual rules for name lookup in
1593 // unqualified function calls (3.4.2) except that all member
1594 // functions are ignored. However, if no operand has a class
1595 // type, only those non-member functions in the lookup set
1596 // that have a first parameter of type T1 or “reference to
1597 // (possibly cv-qualified) T1”, when T1 is an enumeration
1598 // type, or (if there is a right operand) a second parameter
1599 // of type T2 or “reference to (possibly cv-qualified) T2”,
1600 // when T2 is an enumeration type, are candidate functions.
1601 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1602 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1603
1604 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1605
1606 if (!Operators)
1607 return;
1608
1609 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1610 Op != OpEnd; ++Op) {
1611 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1612 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1613 Functions.insert(FD); // FIXME: canonical FD
1614 }
1615}
1616
1617void Sema::ArgumentDependentLookup(DeclarationName Name,
1618 Expr **Args, unsigned NumArgs,
1619 FunctionSet &Functions) {
1620 // Find all of the associated namespaces and classes based on the
1621 // arguments we have.
1622 AssociatedNamespaceSet AssociatedNamespaces;
1623 AssociatedClassSet AssociatedClasses;
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001624 bool GlobalScope = false;
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001625 FindAssociatedClassesAndNamespaces(Args, NumArgs,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001626 AssociatedNamespaces, AssociatedClasses,
1627 GlobalScope);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001628
1629 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001630 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1631 // and let Y be the lookup set produced by argument dependent
1632 // lookup (defined as follows). If X contains [...] then Y is
1633 // empty. Otherwise Y is the set of declarations found in the
1634 // namespaces associated with the argument types as described
1635 // below. The set of declarations found by the lookup of the name
1636 // is the union of X and Y.
1637 //
1638 // Here, we compute Y and add its members to the overloaded
1639 // candidate set.
1640 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1641 NSEnd = AssociatedNamespaces.end();
1642 NS != NSEnd; ++NS) {
1643 // When considering an associated namespace, the lookup is the
1644 // same as the lookup performed when the associated namespace is
1645 // used as a qualifier (3.4.3.2) except that:
1646 //
1647 // -- Any using-directives in the associated namespace are
1648 // ignored.
1649 //
1650 // -- FIXME: Any namespace-scope friend functions declared in
1651 // associated classes are visible within their respective
1652 // namespaces even if they are not visible during an ordinary
1653 // lookup (11.4).
1654 DeclContext::lookup_iterator I, E;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001655 for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001656 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1657 if (!Func)
1658 break;
1659
1660 Functions.insert(Func);
1661 }
1662 }
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001663
1664 if (GlobalScope) {
1665 DeclContext::lookup_iterator I, E;
1666 for (llvm::tie(I, E)
1667 = Context.getTranslationUnitDecl()->lookup(Context, Name);
1668 I != E; ++I) {
1669 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1670 if (!Func)
1671 break;
1672
1673 Functions.insert(Func);
1674 }
1675 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001676}