blob: 1ca3412620369bad242d70d277fd696d36810586 [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 Gregordaa439a2009-07-08 10:57:20 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000023#include "clang/Parse/DeclSpec.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000025#include "clang/Basic/LangOptions.h"
26#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000027#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000028#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000029#include <vector>
30#include <iterator>
31#include <utility>
32#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000033
34using namespace clang;
35
Douglas Gregor2a3009a2009-02-03 19:21:40 +000036typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
37typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
38typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
39
40/// UsingDirAncestorCompare - Implements strict weak ordering of
41/// UsingDirectives. It orders them by address of its common ancestor.
42struct UsingDirAncestorCompare {
43
44 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
45 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
46 return U->getCommonAncestor() < Ctx;
47 }
48
49 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
50 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
51 return Ctx < U->getCommonAncestor();
52 }
53
54 /// @brief Compares UsingDirectiveDecl common ancestors.
55 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
56 return U1->getCommonAncestor() < U2->getCommonAncestor();
57 }
58};
59
60/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
61/// (ordered by common ancestors), found in namespace NS,
62/// including all found (recursively) in their nominated namespaces.
Douglas Gregor6ab35242009-04-09 21:40:53 +000063void AddNamespaceUsingDirectives(ASTContext &Context,
64 DeclContext *NS,
Douglas Gregor2a3009a2009-02-03 19:21:40 +000065 UsingDirectivesTy &UDirs,
66 NamespaceSet &Visited) {
67 DeclContext::udir_iterator I, End;
68
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000069 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +000070 UDirs.push_back(*I);
71 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
72 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
73 if (Visited.insert(Nominated).second)
Douglas Gregor6ab35242009-04-09 21:40:53 +000074 AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
Douglas Gregor2a3009a2009-02-03 19:21:40 +000075 }
76}
77
78/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
79/// including all found in the namespaces they nominate.
Douglas Gregor6ab35242009-04-09 21:40:53 +000080static void AddScopeUsingDirectives(ASTContext &Context, Scope *S,
81 UsingDirectivesTy &UDirs) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +000082 NamespaceSet VisitedNS;
83
84 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
85
86 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
87 VisitedNS.insert(NS);
88
Douglas Gregor6ab35242009-04-09 21:40:53 +000089 AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
Douglas Gregor2a3009a2009-02-03 19:21:40 +000090
91 } else {
Chris Lattnerb28317a2009-03-28 19:18:32 +000092 Scope::udir_iterator I = S->using_directives_begin(),
93 End = S->using_directives_end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +000094
95 for (; I != End; ++I) {
Chris Lattnerb28317a2009-03-28 19:18:32 +000096 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
Douglas Gregor2a3009a2009-02-03 19:21:40 +000097 UDirs.push_back(UD);
98 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
99
100 NamespaceDecl *Nominated = UD->getNominatedNamespace();
101 if (!VisitedNS.count(Nominated)) {
102 VisitedNS.insert(Nominated);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000103 AddNamespaceUsingDirectives(Context, Nominated, UDirs,
104 /*ref*/ VisitedNS);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000105 }
106 }
107 }
108}
109
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000110/// MaybeConstructOverloadSet - Name lookup has determined that the
111/// elements in [I, IEnd) have the name that we are looking for, and
112/// *I is a match for the namespace. This routine returns an
113/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000114/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000115/// [I, IEnd).
116///
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000117/// The existance of this routine is temporary; users of LookupResult
118/// should be able to handle multiple results, to deal with cases of
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000119/// ambiguity and overloaded functions without needing to create a
120/// Decl node.
121template<typename DeclIterator>
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000122static NamedDecl *
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000123MaybeConstructOverloadSet(ASTContext &Context,
124 DeclIterator I, DeclIterator IEnd) {
125 assert(I != IEnd && "Iterator range cannot be empty");
126 assert(!isa<OverloadedFunctionDecl>(*I) &&
127 "Cannot have an overloaded function");
128
Douglas Gregore53060f2009-06-25 22:08:12 +0000129 if ((*I)->isFunctionOrFunctionTemplate()) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000130 // If we found a function, there might be more functions. If
131 // so, collect them into an overload set.
132 DeclIterator Last = I;
133 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000134 for (++Last;
135 Last != IEnd && (*Last)->isFunctionOrFunctionTemplate();
136 ++Last) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000137 if (!Ovl) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000138 // FIXME: We leak this overload set. Eventually, we want to stop
139 // building the declarations for these overload sets, so there will be
140 // nothing to leak.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000141 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000142 (*I)->getDeclName());
Anders Carlssone136e0e2009-06-26 06:29:23 +0000143 NamedDecl *ND = (*I)->getUnderlyingDecl();
Anders Carlsson58badb72009-06-26 05:26:50 +0000144 if (isa<FunctionDecl>(ND))
145 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregore53060f2009-06-25 22:08:12 +0000146 else
Anders Carlsson58badb72009-06-26 05:26:50 +0000147 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000148 }
Douglas Gregore53060f2009-06-25 22:08:12 +0000149
Anders Carlssone136e0e2009-06-26 06:29:23 +0000150 NamedDecl *ND = (*Last)->getUnderlyingDecl();
Anders Carlsson58badb72009-06-26 05:26:50 +0000151 if (isa<FunctionDecl>(ND))
152 Ovl->addOverload(cast<FunctionDecl>(ND));
Douglas Gregore53060f2009-06-25 22:08:12 +0000153 else
Anders Carlsson58badb72009-06-26 05:26:50 +0000154 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000155 }
156
157 // If we had more than one function, we built an overload
158 // set. Return it.
159 if (Ovl)
160 return Ovl;
161 }
162
163 return *I;
164}
165
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000166/// Merges together multiple LookupResults dealing with duplicated Decl's.
167static Sema::LookupResult
168MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
169 typedef Sema::LookupResult LResult;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000170 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000171
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000172 // Remove duplicated Decl pointing at same Decl, by storing them in
173 // associative collection. This might be case for code like:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000174 //
175 // namespace A { int i; }
176 // namespace B { using namespace A; }
177 // namespace C { using namespace A; }
178 //
179 // void foo() {
180 // using namespace B;
181 // using namespace C;
182 // ++i; // finds A::i, from both namespace B and C at global scope
183 // }
184 //
185 // C++ [namespace.qual].p3:
186 // The same declaration found more than once is not an ambiguity
187 // (because it is still a unique declaration).
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000188 DeclsSetTy FoundDecls;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000189
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000190 // Counter of tag names, and functions for resolving ambiguity
191 // and name hiding.
192 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000193
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000194 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
195
196 // No name lookup results, return early.
197 if (I == End) return LResult::CreateLookupResult(Context, 0);
198
199 // Keep track of the tag declaration we found. We only use this if
200 // we find a single tag declaration.
201 TagDecl *TagFound = 0;
202
203 for (; I != End; ++I) {
204 switch (I->getKind()) {
205 case LResult::NotFound:
206 assert(false &&
207 "Should be always successful name lookup result here.");
208 break;
209
210 case LResult::AmbiguousReference:
211 case LResult::AmbiguousBaseSubobjectTypes:
212 case LResult::AmbiguousBaseSubobjects:
213 assert(false && "Shouldn't get ambiguous lookup here.");
214 break;
215
216 case LResult::Found: {
Anders Carlssone136e0e2009-06-26 06:29:23 +0000217 NamedDecl *ND = I->getAsDecl()->getUnderlyingDecl();
Anders Carlssonbc13ab22009-06-26 03:54:13 +0000218
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000219 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
220 TagFound = Context.getCanonicalDecl(TD);
221 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
Douglas Gregore53060f2009-06-25 22:08:12 +0000222 } else if (ND->isFunctionOrFunctionTemplate())
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000223 Functions += FoundDecls.insert(ND)? 1 : 0;
224 else
225 FoundDecls.insert(ND);
226 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000227 }
228
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000229 case LResult::FoundOverloaded:
230 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
231 Functions += FoundDecls.insert(*FI)? 1 : 0;
232 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000233 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000234 }
235 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
236 bool Ambiguous = false, NameHidesTags = false;
237
238 if (FoundDecls.size() == 1) {
239 // 1) Exactly one result.
240 } else if (TagNames > 1) {
241 // 2) Multiple tag names (even though they may be hidden by an
242 // object name).
243 Ambiguous = true;
244 } else if (FoundDecls.size() - TagNames == 1) {
245 // 3) Ordinary name hides (optional) tag.
246 NameHidesTags = TagFound;
247 } else if (Functions) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000248 // C++ [basic.lookup].p1:
249 // ... Name lookup may associate more than one declaration with
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000250 // a name if it finds the name to be a function name; the declarations
251 // are said to form a set of overloaded functions (13.1).
252 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000253 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000254 if (!OrdinaryNonFunc) {
255 // 4) Functions hide tag names.
256 NameHidesTags = TagFound;
257 } else {
258 // 5) Functions + ordinary names.
259 Ambiguous = true;
260 }
261 } else {
262 // 6) Multiple non-tag names
263 Ambiguous = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000264 }
265
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000266 if (Ambiguous)
267 return LResult::CreateLookupResult(Context,
268 FoundDecls.begin(), FoundDecls.size());
269 if (NameHidesTags) {
270 // There's only one tag, TagFound. Remove it.
271 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
272 FoundDecls.erase(TagFound);
273 }
274
275 // Return successful name lookup result.
276 return LResult::CreateLookupResult(Context,
277 MaybeConstructOverloadSet(Context,
278 FoundDecls.begin(),
279 FoundDecls.end()));
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000280}
281
282// Retrieve the set of identifier namespaces that correspond to a
283// specific kind of name lookup.
284inline unsigned
285getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
286 bool CPlusPlus) {
287 unsigned IDNS = 0;
288 switch (NameKind) {
289 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000290 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000291 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000292 IDNS = Decl::IDNS_Ordinary;
293 if (CPlusPlus)
294 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
295 break;
296
297 case Sema::LookupTagName:
298 IDNS = Decl::IDNS_Tag;
299 break;
300
301 case Sema::LookupMemberName:
302 IDNS = Decl::IDNS_Member;
303 if (CPlusPlus)
304 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
305 break;
306
307 case Sema::LookupNestedNameSpecifierName:
308 case Sema::LookupNamespaceName:
309 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
310 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000311
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000312 case Sema::LookupObjCProtocolName:
313 IDNS = Decl::IDNS_ObjCProtocol;
314 break;
315
316 case Sema::LookupObjCImplementationName:
317 IDNS = Decl::IDNS_ObjCImplementation;
318 break;
319
320 case Sema::LookupObjCCategoryImplName:
321 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000322 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000323 }
324 return IDNS;
325}
326
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000327Sema::LookupResult
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000328Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Anders Carlssone136e0e2009-06-26 06:29:23 +0000329 if (D)
330 D = D->getUnderlyingDecl();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000331
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000332 LookupResult Result;
333 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
334 OverloadedDeclSingleDecl : SingleDecl;
335 Result.First = reinterpret_cast<uintptr_t>(D);
336 Result.Last = 0;
337 Result.Context = &Context;
338 return Result;
339}
340
Douglas Gregor4bb64e72009-01-15 02:19:31 +0000341/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000342Sema::LookupResult
343Sema::LookupResult::CreateLookupResult(ASTContext &Context,
344 IdentifierResolver::iterator F,
345 IdentifierResolver::iterator L) {
346 LookupResult Result;
347 Result.Context = &Context;
348
Douglas Gregore53060f2009-06-25 22:08:12 +0000349 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000350 IdentifierResolver::iterator Next = F;
351 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000352 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000353 Result.StoredKind = OverloadedDeclFromIdResolver;
354 Result.First = F.getAsOpaqueValue();
355 Result.Last = L.getAsOpaqueValue();
356 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000357 }
358 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000359
Anders Carlssone136e0e2009-06-26 06:29:23 +0000360 NamedDecl *D = *F;
361 if (D)
362 D = D->getUnderlyingDecl();
Anders Carlsson8b50d012009-06-26 03:37:05 +0000363
Douglas Gregor69d993a2009-01-17 01:13:24 +0000364 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000365 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000366 Result.Last = 0;
367 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000368}
369
Douglas Gregor69d993a2009-01-17 01:13:24 +0000370Sema::LookupResult
371Sema::LookupResult::CreateLookupResult(ASTContext &Context,
372 DeclContext::lookup_iterator F,
373 DeclContext::lookup_iterator L) {
374 LookupResult Result;
375 Result.Context = &Context;
376
Douglas Gregore53060f2009-06-25 22:08:12 +0000377 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
Douglas Gregor7176fff2009-01-15 00:26:24 +0000378 DeclContext::lookup_iterator Next = F;
379 ++Next;
Douglas Gregore53060f2009-06-25 22:08:12 +0000380 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000381 Result.StoredKind = OverloadedDeclFromDeclContext;
382 Result.First = reinterpret_cast<uintptr_t>(F);
383 Result.Last = reinterpret_cast<uintptr_t>(L);
384 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000385 }
386 }
Douglas Gregor516ff432009-04-24 02:57:34 +0000387
Anders Carlssone136e0e2009-06-26 06:29:23 +0000388 NamedDecl *D = *F;
389 if (D)
390 D = D->getUnderlyingDecl();
391
Douglas Gregor69d993a2009-01-17 01:13:24 +0000392 Result.StoredKind = SingleDecl;
Douglas Gregor516ff432009-04-24 02:57:34 +0000393 Result.First = reinterpret_cast<uintptr_t>(D);
Douglas Gregor69d993a2009-01-17 01:13:24 +0000394 Result.Last = 0;
395 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000396}
397
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000398/// @brief Determine the result of name lookup.
399Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
400 switch (StoredKind) {
401 case SingleDecl:
402 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
403
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000404 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000405 case OverloadedDeclFromIdResolver:
406 case OverloadedDeclFromDeclContext:
407 return FoundOverloaded;
408
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000409 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000410 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000411
412 case AmbiguousLookupStoresDecls:
413 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000414 }
415
Douglas Gregor7176fff2009-01-15 00:26:24 +0000416 // We can't ever get here.
417 return NotFound;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000418}
419
420/// @brief Converts the result of name lookup into a single (possible
421/// NULL) pointer to a declaration.
422///
423/// The resulting declaration will either be the declaration we found
424/// (if only a single declaration was found), an
425/// OverloadedFunctionDecl (if an overloaded function was found), or
426/// NULL (if no declaration was found). This conversion must not be
427/// used anywhere where name lookup could result in an ambiguity.
428///
429/// The OverloadedFunctionDecl conversion is meant as a stop-gap
430/// solution, since it causes the OverloadedFunctionDecl to be
431/// leaked. FIXME: Eventually, there will be a better way to iterate
432/// over the set of overloaded functions returned by name lookup.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000433NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000434 switch (StoredKind) {
435 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000436 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000437
438 case OverloadedDeclFromIdResolver:
439 return MaybeConstructOverloadSet(*Context,
440 IdentifierResolver::iterator::getFromOpaqueValue(First),
441 IdentifierResolver::iterator::getFromOpaqueValue(Last));
442
443 case OverloadedDeclFromDeclContext:
444 return MaybeConstructOverloadSet(*Context,
445 reinterpret_cast<DeclContext::lookup_iterator>(First),
446 reinterpret_cast<DeclContext::lookup_iterator>(Last));
447
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000448 case OverloadedDeclSingleDecl:
449 return reinterpret_cast<OverloadedFunctionDecl*>(First);
450
451 case AmbiguousLookupStoresDecls:
452 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000453 assert(false &&
454 "Name lookup returned an ambiguity that could not be handled");
455 break;
456 }
457
458 return 0;
459}
460
Douglas Gregor7176fff2009-01-15 00:26:24 +0000461/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000462/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000463BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000464 if (StoredKind == AmbiguousLookupStoresBasePaths)
465 return reinterpret_cast<BasePaths *>(First);
466 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000467}
468
Douglas Gregord8635172009-02-02 21:35:47 +0000469Sema::LookupResult::iterator::reference
470Sema::LookupResult::iterator::operator*() const {
471 switch (Result->StoredKind) {
472 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000473 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000474
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000475 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000476 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000477
Douglas Gregord8635172009-02-02 21:35:47 +0000478 case OverloadedDeclFromIdResolver:
479 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
480
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000481 case AmbiguousLookupStoresBasePaths:
Douglas Gregor31a19b62009-04-01 21:51:26 +0000482 if (Result->Last)
483 return *reinterpret_cast<NamedDecl**>(Current);
484
485 // Fall through to handle the DeclContext::lookup_iterator we're
486 // storing.
487
488 case OverloadedDeclFromDeclContext:
489 case AmbiguousLookupStoresDecls:
490 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000491 }
492
493 return 0;
494}
495
496Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
497 switch (Result->StoredKind) {
498 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000499 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000500 break;
501
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000502 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000503 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000504 ++I;
505 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000506 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000507 }
508
Douglas Gregord8635172009-02-02 21:35:47 +0000509 case OverloadedDeclFromIdResolver: {
510 IdentifierResolver::iterator I
511 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
512 ++I;
513 Current = I.getAsOpaqueValue();
514 break;
515 }
516
Douglas Gregor31a19b62009-04-01 21:51:26 +0000517 case AmbiguousLookupStoresBasePaths:
518 if (Result->Last) {
519 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
520 ++I;
521 Current = reinterpret_cast<uintptr_t>(I);
522 break;
523 }
524 // Fall through to handle the DeclContext::lookup_iterator we're
525 // storing.
526
527 case OverloadedDeclFromDeclContext:
528 case AmbiguousLookupStoresDecls: {
Douglas Gregord8635172009-02-02 21:35:47 +0000529 DeclContext::lookup_iterator I
530 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
531 ++I;
532 Current = reinterpret_cast<uintptr_t>(I);
533 break;
534 }
Douglas Gregord8635172009-02-02 21:35:47 +0000535 }
536
537 return *this;
538}
539
540Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000541 switch (StoredKind) {
542 case SingleDecl:
543 case OverloadedDeclFromIdResolver:
544 case OverloadedDeclFromDeclContext:
545 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000546 return iterator(this, First);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000547
548 case OverloadedDeclSingleDecl: {
549 OverloadedFunctionDecl * Ovl =
550 reinterpret_cast<OverloadedFunctionDecl*>(First);
551 return iterator(this,
552 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
553 }
554
555 case AmbiguousLookupStoresBasePaths:
556 if (Last)
557 return iterator(this,
558 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
559 else
560 return iterator(this,
561 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
562 }
563
564 // Required to suppress GCC warning.
565 return iterator();
Douglas Gregord8635172009-02-02 21:35:47 +0000566}
567
568Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000569 switch (StoredKind) {
570 case SingleDecl:
571 case OverloadedDeclFromIdResolver:
572 case OverloadedDeclFromDeclContext:
573 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000574 return iterator(this, Last);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000575
576 case OverloadedDeclSingleDecl: {
577 OverloadedFunctionDecl * Ovl =
578 reinterpret_cast<OverloadedFunctionDecl*>(First);
579 return iterator(this,
580 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
581 }
582
583 case AmbiguousLookupStoresBasePaths:
584 if (Last)
585 return iterator(this,
586 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
587 else
588 return iterator(this, reinterpret_cast<uintptr_t>(
589 getBasePaths()->front().Decls.second));
590 }
591
592 // Required to suppress GCC warning.
593 return iterator();
594}
595
596void Sema::LookupResult::Destroy() {
597 if (BasePaths *Paths = getBasePaths())
598 delete Paths;
599 else if (getKind() == AmbiguousReference)
600 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregord8635172009-02-02 21:35:47 +0000601}
602
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000603static void
604CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
605 DeclarationName Name, Sema::LookupNameKind NameKind,
606 unsigned IDNS, LookupResultsTy &Results,
607 UsingDirectivesTy *UDirs = 0) {
608
609 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
610
611 // Perform qualified name lookup into the LookupCtx.
612 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000613 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000614 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
615 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
616 break;
617 }
618
619 if (UDirs) {
620 // For each UsingDirectiveDecl, which common ancestor is equal
621 // to NS, we preform qualified name lookup into namespace nominated by it.
622 UsingDirectivesTy::const_iterator UI, UEnd;
623 llvm::tie(UI, UEnd) =
624 std::equal_range(UDirs->begin(), UDirs->end(), NS,
625 UsingDirAncestorCompare());
626
627 for (; UI != UEnd; ++UI)
628 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
629 Name, NameKind, IDNS, Results);
630 }
631}
632
633static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000634 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000635 return Ctx->isFileContext();
636 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000637}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000638
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000639std::pair<bool, Sema::LookupResult>
640Sema::CppLookupName(Scope *S, DeclarationName Name,
641 LookupNameKind NameKind, bool RedeclarationOnly) {
642 assert(getLangOptions().CPlusPlus &&
643 "Can perform only C++ lookup");
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000644 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000645 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000646 Scope *Initial = S;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000647 DeclContext *OutOfLineCtx = 0;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000648 IdentifierResolver::iterator
649 I = IdResolver.begin(Name),
650 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000651
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000652 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000653 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000654 // ...During unqualified name lookup (3.4.1), the names appear as if
655 // they were declared in the nearest enclosing namespace which contains
656 // both the using-directive and the nominated namespace.
657 // [Note: in this context, “contains” means “contains directly or
658 // indirectly”.
659 //
660 // For example:
661 // namespace A { int i; }
662 // void foo() {
663 // int i;
664 // {
665 // using namespace A;
666 // ++i; // finds local 'i', A::i appears at global scope
667 // }
668 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000669 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000670 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000671 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000672 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000673 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
674 // We found something. Look for anything else in our scope
675 // with this same name and in an acceptable identifier
676 // namespace, so that we can construct an overload set if we
677 // need to.
678 IdentifierResolver::iterator LastI = I;
679 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000680 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000681 break;
682 }
683 LookupResult Result =
684 LookupResult::CreateLookupResult(Context, I, LastI);
685 return std::make_pair(true, Result);
686 }
687 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000688 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
689 LookupResult R;
690 // Perform member lookup into struct.
Mike Stump390b4cc2009-05-16 07:39:55 +0000691 // FIXME: In some cases, we know that every name that could be found by
692 // this qualified name lookup will also be on the identifier chain. For
693 // example, inside a class without any base classes, we never need to
694 // perform qualified lookup because all of the members are on top of the
695 // identifier chain.
Douglas Gregor551f48c2009-03-27 04:21:56 +0000696 if (isa<RecordDecl>(Ctx)) {
697 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000698 if (R)
Douglas Gregor551f48c2009-03-27 04:21:56 +0000699 return std::make_pair(true, R);
700 }
Douglas Gregor2bba76b2009-05-27 17:07:49 +0000701 if (Ctx->getParent() != Ctx->getLexicalParent()
702 || isa<CXXMethodDecl>(Ctx)) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000703 // It is out of line defined C++ method or struct, we continue
704 // doing name lookup in parent context. Once we will find namespace
705 // or translation-unit we save it for possible checking
706 // using-directives later.
707 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
708 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregor551f48c2009-03-27 04:21:56 +0000709 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
Douglas Gregorc19ee3e2009-06-17 23:37:01 +0000710 if (R)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000711 return std::make_pair(true, R);
712 }
713 }
714 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000715 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000716
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000717 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000718 // nominated namespaces by those using-directives.
Mike Stump390b4cc2009-05-16 07:39:55 +0000719 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
720 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
721 // don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000722 UsingDirectivesTy UDirs;
723 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000724 if (SC->getFlags() & Scope::DeclScope)
Douglas Gregor6ab35242009-04-09 21:40:53 +0000725 AddScopeUsingDirectives(Context, SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000726
727 // Sort heapified UsingDirectiveDecls.
Douglas Gregorb738e082009-05-18 22:06:54 +0000728 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000729
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000730 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000731 // Unqualified name lookup in C++ requires looking into scopes
732 // that aren't strictly lexical, and therefore we walk through the
733 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000734
735 LookupResultsTy LookupResults;
Sebastian Redl22460502009-02-07 00:15:38 +0000736 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000737 "We should have been looking only at file context here already.");
738 bool LookedInCtx = false;
739 LookupResult Result;
740 while (OutOfLineCtx &&
741 OutOfLineCtx != S->getEntity() &&
742 OutOfLineCtx->isNamespace()) {
743 LookedInCtx = true;
744
745 // Look into context considering using-directives.
746 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
747 LookupResults, &UDirs);
748
749 if ((Result = MergeLookupResults(Context, LookupResults)) ||
750 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
751 return std::make_pair(true, Result);
752
753 OutOfLineCtx = OutOfLineCtx->getParent();
754 }
755
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000756 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000757 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
758 assert(Ctx && Ctx->isFileContext() &&
759 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000760
761 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000762 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000763 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
764 // We found something. Look for anything else in our scope
765 // with this same name and in an acceptable identifier
766 // namespace, so that we can construct an overload set if we
767 // need to.
768 IdentifierResolver::iterator LastI = I;
769 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000770 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000771 break;
772 }
773
774 // We store name lookup result, and continue trying to look into
775 // associated context, and maybe namespaces nominated by
776 // using-directives.
777 LookupResults.push_back(
778 LookupResult::CreateLookupResult(Context, I, LastI));
779 break;
780 }
781 }
782
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000783 LookedInCtx = true;
784 // Look into context considering using-directives.
785 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
786 LookupResults, &UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000787
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000788 if ((Result = MergeLookupResults(Context, LookupResults)) ||
789 (RedeclarationOnly && !Ctx->isTransparentContext()))
790 return std::make_pair(true, Result);
791 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000792
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000793 if (!(LookedInCtx || LookupResults.empty())) {
794 // We didn't Performed lookup in Scope entity, so we return
795 // result form IdentifierResolver.
796 assert((LookupResults.size() == 1) && "Wrong size!");
797 return std::make_pair(true, LookupResults.front());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000798 }
799 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000800}
801
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000802/// @brief Perform unqualified name lookup starting from a given
803/// scope.
804///
805/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
806/// used to find names within the current scope. For example, 'x' in
807/// @code
808/// int x;
809/// int f() {
810/// return x; // unqualified name look finds 'x' in the global scope
811/// }
812/// @endcode
813///
814/// Different lookup criteria can find different names. For example, a
815/// particular scope can have both a struct and a function of the same
816/// name, and each can be found by certain lookup criteria. For more
817/// information about lookup criteria, see the documentation for the
818/// class LookupCriteria.
819///
820/// @param S The scope from which unqualified name lookup will
821/// begin. If the lookup criteria permits, name lookup may also search
822/// in the parent scopes.
823///
824/// @param Name The name of the entity that we are searching for.
825///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000826/// @param Loc If provided, the source location where we're performing
827/// name lookup. At present, this is only used to produce diagnostics when
828/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000829///
830/// @returns The result of name lookup, which includes zero or more
831/// declarations and possibly additional information used to diagnose
832/// ambiguities.
833Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000834Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000835 bool RedeclarationOnly, bool AllowBuiltinCreation,
836 SourceLocation Loc) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000837 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000838
839 if (!getLangOptions().CPlusPlus) {
840 // Unqualified name lookup in C/Objective-C is purely lexical, so
841 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000842 unsigned IDNS = 0;
843 switch (NameKind) {
844 case Sema::LookupOrdinaryName:
845 IDNS = Decl::IDNS_Ordinary;
846 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000847
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000848 case Sema::LookupTagName:
849 IDNS = Decl::IDNS_Tag;
850 break;
851
852 case Sema::LookupMemberName:
853 IDNS = Decl::IDNS_Member;
854 break;
855
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000856 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000857 case Sema::LookupNestedNameSpecifierName:
858 case Sema::LookupNamespaceName:
859 assert(false && "C does not perform these kinds of name lookup");
860 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000861
862 case Sema::LookupRedeclarationWithLinkage:
863 // Find the nearest non-transparent declaration scope.
864 while (!(S->getFlags() & Scope::DeclScope) ||
865 (S->getEntity() &&
866 static_cast<DeclContext *>(S->getEntity())
867 ->isTransparentContext()))
868 S = S->getParent();
869 IDNS = Decl::IDNS_Ordinary;
870 break;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000871
Douglas Gregor8fc463a2009-04-24 00:11:27 +0000872 case Sema::LookupObjCProtocolName:
873 IDNS = Decl::IDNS_ObjCProtocol;
874 break;
875
876 case Sema::LookupObjCImplementationName:
877 IDNS = Decl::IDNS_ObjCImplementation;
878 break;
879
880 case Sema::LookupObjCCategoryImplName:
881 IDNS = Decl::IDNS_ObjCCategoryImpl;
Douglas Gregor6e378de2009-04-23 23:18:26 +0000882 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000883 }
884
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000885 // Scan up the scope chain looking for a decl that matches this
886 // identifier that is in the appropriate namespace. This search
887 // should not take long, as shadowing of names is uncommon, and
888 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000889 bool LeftStartingScope = false;
890
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000891 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
892 IEnd = IdResolver.end();
893 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000894 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000895 if (NameKind == LookupRedeclarationWithLinkage) {
896 // Determine whether this (or a previous) declaration is
897 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000898 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000899 LeftStartingScope = true;
900
901 // If we found something outside of our starting scope that
902 // does not have linkage, skip it.
903 if (LeftStartingScope && !((*I)->hasLinkage()))
904 continue;
905 }
906
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000907 if ((*I)->getAttr<OverloadableAttr>()) {
Douglas Gregorf9201e02009-02-11 23:02:49 +0000908 // If this declaration has the "overloadable" attribute, we
909 // might have a set of overloaded functions.
910
911 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000912 while (!(S->getFlags() & Scope::DeclScope) ||
913 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000914 S = S->getParent();
915
916 // Find the last declaration in this scope (with the same
917 // name, naturally).
918 IdentifierResolver::iterator LastI = I;
919 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000920 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000921 break;
922 }
923
924 return LookupResult::CreateLookupResult(Context, I, LastI);
925 }
926
927 // We have a single lookup result.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000928 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000929 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000930 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000931 // Perform C++ unqualified name lookup.
932 std::pair<bool, LookupResult> MaybeResult =
933 CppLookupName(S, Name, NameKind, RedeclarationOnly);
934 if (MaybeResult.first)
935 return MaybeResult.second;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000936 }
937
938 // If we didn't find a use of this identifier, and if the identifier
939 // corresponds to a compiler builtin, create the decl object for the builtin
940 // now, injecting it into translation unit scope, and return it.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000941 if (NameKind == LookupOrdinaryName ||
942 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000943 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000944 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000945 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000946 if (unsigned BuiltinID = II->getBuiltinID()) {
947 // In C++, we don't have any predefined library functions like
948 // 'malloc'. Instead, we'll just error.
949 if (getLangOptions().CPlusPlus &&
950 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
951 return LookupResult::CreateLookupResult(Context, 0);
952
Douglas Gregor69d993a2009-01-17 01:13:24 +0000953 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000954 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000955 S, RedeclarationOnly, Loc));
956 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000957 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000958 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000959 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000960}
961
962/// @brief Perform qualified name lookup into a given context.
963///
964/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
965/// names when the context of those names is explicit specified, e.g.,
966/// "std::vector" or "x->member".
967///
968/// Different lookup criteria can find different names. For example, a
969/// particular scope can have both a struct and a function of the same
970/// name, and each can be found by certain lookup criteria. For more
971/// information about lookup criteria, see the documentation for the
972/// class LookupCriteria.
973///
974/// @param LookupCtx The context in which qualified name lookup will
975/// search. If the lookup criteria permits, name lookup may also search
976/// in the parent contexts or (for C++ classes) base classes.
977///
978/// @param Name The name of the entity that we are searching for.
979///
980/// @param Criteria The criteria that this routine will use to
981/// determine which names are visible and which names will be
982/// found. Note that name lookup will find a name that is visible by
983/// the given criteria, but the entity itself may not be semantically
984/// correct or even the kind of entity expected based on the
985/// lookup. For example, searching for a nested-name-specifier name
986/// might result in an EnumDecl, which is visible but is not permitted
987/// as a nested-name-specifier in C++03.
988///
989/// @returns The result of name lookup, which includes zero or more
990/// declarations and possibly additional information used to diagnose
991/// ambiguities.
992Sema::LookupResult
993Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000994 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000995 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
996
Douglas Gregor69d993a2009-01-17 01:13:24 +0000997 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000998
999 // If we're performing qualified name lookup (e.g., lookup into a
1000 // struct), find fields as part of ordinary name lookup.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001001 unsigned IDNS
1002 = getIdentifierNamespacesFromLookupNameKind(NameKind,
1003 getLangOptions().CPlusPlus);
1004 if (NameKind == LookupOrdinaryName)
1005 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001006
1007 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001008 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001009 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001010 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001011 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001012
Douglas Gregor7176fff2009-01-15 00:26:24 +00001013 // If this isn't a C++ class or we aren't allowed to look into base
1014 // classes, we're done.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001015 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001016 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001017
1018 // Perform lookup into our base classes.
1019 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001020 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +00001021
1022 // Look for this member in our base classes
1023 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001024 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001025 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001026
1027 // C++ [class.member.lookup]p2:
1028 // [...] If the resulting set of declarations are not all from
1029 // sub-objects of the same type, or the set has a nonstatic member
1030 // and includes members from distinct sub-objects, there is an
1031 // ambiguity and the program is ill-formed. Otherwise that set is
1032 // the result of the lookup.
1033 // FIXME: support using declarations!
1034 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +00001035 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001036 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1037 Path != PathEnd; ++Path) {
1038 const BasePathElement &PathElement = Path->back();
1039
1040 // Determine whether we're looking at a distinct sub-object or not.
1041 if (SubobjectType.isNull()) {
1042 // This is the first subobject we've looked at. Record it's type.
1043 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1044 SubobjectNumber = PathElement.SubobjectNumber;
1045 } else if (SubobjectType
1046 != Context.getCanonicalType(PathElement.Base->getType())) {
1047 // We found members of the given name in two subobjects of
1048 // different types. This lookup is ambiguous.
1049 BasePaths *PathsOnHeap = new BasePaths;
1050 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001051 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001052 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1053 // We have a different subobject of the same type.
1054
1055 // C++ [class.member.lookup]p5:
1056 // A static member, a nested type or an enumerator defined in
1057 // a base class T can unambiguously be found even if an object
1058 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001059 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001060 if (isa<VarDecl>(FirstDecl) ||
1061 isa<TypeDecl>(FirstDecl) ||
1062 isa<EnumConstantDecl>(FirstDecl))
1063 continue;
1064
1065 if (isa<CXXMethodDecl>(FirstDecl)) {
1066 // Determine whether all of the methods are static.
1067 bool AllMethodsAreStatic = true;
1068 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1069 Func != Path->Decls.second; ++Func) {
1070 if (!isa<CXXMethodDecl>(*Func)) {
1071 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1072 break;
1073 }
1074
1075 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1076 AllMethodsAreStatic = false;
1077 break;
1078 }
1079 }
1080
1081 if (AllMethodsAreStatic)
1082 continue;
1083 }
1084
1085 // We have found a nonstatic member name in multiple, distinct
1086 // subobjects. Name lookup is ambiguous.
1087 BasePaths *PathsOnHeap = new BasePaths;
1088 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001089 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001090 }
1091 }
1092
1093 // Lookup in a base class succeeded; return these results.
1094
1095 // If we found a function declaration, return an overload set.
Douglas Gregore53060f2009-06-25 22:08:12 +00001096 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
Douglas Gregor69d993a2009-01-17 01:13:24 +00001097 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-01-15 00:26:24 +00001098 Paths.front().Decls.first, Paths.front().Decls.second);
1099
1100 // We found a non-function declaration; return a single declaration.
Douglas Gregor69d993a2009-01-17 01:13:24 +00001101 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001102}
1103
1104/// @brief Performs name lookup for a name that was parsed in the
1105/// source code, and may contain a C++ scope specifier.
1106///
1107/// This routine is a convenience routine meant to be called from
1108/// contexts that receive a name and an optional C++ scope specifier
1109/// (e.g., "N::M::x"). It will then perform either qualified or
1110/// unqualified name lookup (with LookupQualifiedName or LookupName,
1111/// respectively) on the given name and return those results.
1112///
1113/// @param S The scope from which unqualified name lookup will
1114/// begin.
1115///
1116/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1117///
1118/// @param Name The name of the entity that name lookup will
1119/// search for.
1120///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001121/// @param Loc If provided, the source location where we're performing
1122/// name lookup. At present, this is only used to produce diagnostics when
1123/// C library functions (like "malloc") are implicitly declared.
1124///
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001125/// @returns The result of qualified or unqualified name lookup.
1126Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001127Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1128 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001129 bool RedeclarationOnly, bool AllowBuiltinCreation,
1130 SourceLocation Loc) {
Douglas Gregor42af25f2009-05-11 19:58:34 +00001131 if (SS && (SS->isSet() || SS->isInvalid())) {
1132 // If the scope specifier is invalid, don't even look for
1133 // anything.
1134 if (SS->isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001135 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001136
Douglas Gregor42af25f2009-05-11 19:58:34 +00001137 assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1138
1139 if (isDependentScopeSpecifier(*SS)) {
1140 // Determine whether we are looking into the current
1141 // instantiation.
1142 NestedNameSpecifier *NNS
1143 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1144 CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1145 assert(Current && "Bad dependent scope specifier");
1146
1147 // We nested name specifier refers to the current instantiation,
1148 // so now we will look for a member of the current instantiation
1149 // (C++0x [temp.dep.type]).
1150 unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1151 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001152 for (llvm::tie(I, E) = Current->lookup(Name); I != E; ++I)
Douglas Gregor42af25f2009-05-11 19:58:34 +00001153 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1154 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001155 }
Douglas Gregor42af25f2009-05-11 19:58:34 +00001156
1157 if (RequireCompleteDeclContext(*SS))
1158 return LookupResult::CreateLookupResult(Context, 0);
1159
1160 return LookupQualifiedName(computeDeclContext(*SS),
1161 Name, NameKind, RedeclarationOnly);
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001162 }
1163
Douglas Gregor9cfbe482009-06-20 00:51:54 +00001164 LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly,
1165 AllowBuiltinCreation, Loc));
1166
1167 return(result);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001168}
1169
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001170
Douglas Gregor7176fff2009-01-15 00:26:24 +00001171/// @brief Produce a diagnostic describing the ambiguity that resulted
1172/// from name lookup.
1173///
1174/// @param Result The ambiguous name lookup result.
1175///
1176/// @param Name The name of the entity that name lookup was
1177/// searching for.
1178///
1179/// @param NameLoc The location of the name within the source code.
1180///
1181/// @param LookupRange A source range that provides more
1182/// source-location information concerning the lookup itself. For
1183/// example, this range might highlight a nested-name-specifier that
1184/// precedes the name.
1185///
1186/// @returns true
1187bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1188 SourceLocation NameLoc,
1189 SourceRange LookupRange) {
1190 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1191
Douglas Gregor31a19b62009-04-01 21:51:26 +00001192 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001193 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1194 QualType SubobjectType = Paths->front().back().Base->getType();
1195 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1196 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1197 << LookupRange;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001198
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001199 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregor31a19b62009-04-01 21:51:26 +00001200 while (isa<CXXMethodDecl>(*Found) &&
1201 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001202 ++Found;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001203
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001204 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1205
Douglas Gregor31a19b62009-04-01 21:51:26 +00001206 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001207 return true;
1208 }
1209
1210 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1211 "Unhandled form of name lookup ambiguity");
1212
1213 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1214 << Name << LookupRange;
1215
1216 std::set<Decl *> DeclsPrinted;
1217 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1218 Path != PathEnd; ++Path) {
1219 Decl *D = *Path->Decls.first;
1220 if (DeclsPrinted.insert(D).second)
1221 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1222 }
1223
Douglas Gregor31a19b62009-04-01 21:51:26 +00001224 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001225 return true;
1226 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001227 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1228
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001229 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregor31a19b62009-04-01 21:51:26 +00001230 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001231
Chris Lattner48458d22009-02-03 21:29:32 +00001232 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001233 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001234
Douglas Gregor31a19b62009-04-01 21:51:26 +00001235 Result.Destroy();
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001236 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001237 }
1238
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001239 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001240
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001241 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001242 return true;
1243}
Douglas Gregorfa047642009-02-04 00:32:51 +00001244
Douglas Gregor69be8d62009-07-08 07:51:57 +00001245static void
1246addAssociatedClassesAndNamespaces(QualType T,
1247 ASTContext &Context,
1248 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1249 Sema::AssociatedClassSet &AssociatedClasses,
1250 bool &GlobalScope);
1251
1252// \brief Add the associated classes and namespaces for argument-dependent
1253// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1254static void
1255addAssociatedClassesAndNamespaces(const TemplateArgument &Arg,
1256 ASTContext &Context,
1257 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1258 Sema::AssociatedClassSet &AssociatedClasses,
1259 bool &GlobalScope) {
1260 // C++ [basic.lookup.koenig]p2, last bullet:
1261 // -- [...] ;
1262 switch (Arg.getKind()) {
1263 case TemplateArgument::Null:
1264 break;
1265
1266 case TemplateArgument::Type:
1267 // [...] the namespaces and classes associated with the types of the
1268 // template arguments provided for template type parameters (excluding
1269 // template template parameters)
1270 addAssociatedClassesAndNamespaces(Arg.getAsType(), Context,
1271 AssociatedNamespaces,
1272 AssociatedClasses,
1273 GlobalScope);
1274 break;
1275
1276 case TemplateArgument::Declaration:
1277 // [...] the namespaces in which any template template arguments are
1278 // defined; and the classes in which any member templates used as
1279 // template template arguments are defined.
1280 if (ClassTemplateDecl *ClassTemplate
1281 = dyn_cast<ClassTemplateDecl>(Arg.getAsDecl())) {
1282 DeclContext *Ctx = ClassTemplate->getDeclContext();
1283 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1284 AssociatedClasses.insert(EnclosingClass);
1285 // Add the associated namespace for this class.
1286 while (Ctx->isRecord())
1287 Ctx = Ctx->getParent();
1288 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1289 AssociatedNamespaces.insert(EnclosingNamespace);
1290 else if (Ctx->isTranslationUnit())
1291 GlobalScope = true;
1292 }
1293 break;
1294
1295 case TemplateArgument::Integral:
1296 case TemplateArgument::Expression:
1297 // [Note: non-type template arguments do not contribute to the set of
1298 // associated namespaces. ]
1299 break;
1300
1301 case TemplateArgument::Pack:
1302 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1303 PEnd = Arg.pack_end();
1304 P != PEnd; ++P)
1305 addAssociatedClassesAndNamespaces(*P, Context,
1306 AssociatedNamespaces,
1307 AssociatedClasses,
1308 GlobalScope);
1309 break;
1310 }
1311}
1312
Douglas Gregorfa047642009-02-04 00:32:51 +00001313// \brief Add the associated classes and namespaces for
1314// argument-dependent lookup with an argument of class type
1315// (C++ [basic.lookup.koenig]p2).
1316static void
1317addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
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 // -- If T is a class type (including unions), its associated
1325 // classes are: the class itself; the class of which it is a
1326 // member, if any; and its direct and indirect base
1327 // classes. Its associated namespaces are the namespaces in
1328 // which its associated classes are defined.
1329
1330 // Add the class of which it is a member, if any.
1331 DeclContext *Ctx = Class->getDeclContext();
1332 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1333 AssociatedClasses.insert(EnclosingClass);
Douglas Gregorfa047642009-02-04 00:32:51 +00001334 // Add the associated namespace for this class.
1335 while (Ctx->isRecord())
1336 Ctx = Ctx->getParent();
1337 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1338 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001339 else if (Ctx->isTranslationUnit())
1340 GlobalScope = true;
1341
Douglas Gregorfa047642009-02-04 00:32:51 +00001342 // Add the class itself. If we've already seen this class, we don't
1343 // need to visit base classes.
1344 if (!AssociatedClasses.insert(Class))
1345 return;
1346
Douglas Gregor69be8d62009-07-08 07:51:57 +00001347 // -- If T is a template-id, its associated namespaces and classes are
1348 // the namespace in which the template is defined; for member
1349 // templates, the member template’s class; the namespaces and classes
1350 // associated with the types of the template arguments provided for
1351 // template type parameters (excluding template template parameters); the
1352 // namespaces in which any template template arguments are defined; and
1353 // the classes in which any member templates used as template template
1354 // arguments are defined. [Note: non-type template arguments do not
1355 // contribute to the set of associated namespaces. ]
1356 if (ClassTemplateSpecializationDecl *Spec
1357 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1358 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1359 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1360 AssociatedClasses.insert(EnclosingClass);
1361 // Add the associated namespace for this class.
1362 while (Ctx->isRecord())
1363 Ctx = Ctx->getParent();
1364 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1365 AssociatedNamespaces.insert(EnclosingNamespace);
1366 else if (Ctx->isTranslationUnit())
1367 GlobalScope = true;
1368
1369 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1370 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1371 addAssociatedClassesAndNamespaces(TemplateArgs[I], Context,
1372 AssociatedNamespaces,
1373 AssociatedClasses,
1374 GlobalScope);
1375 }
1376
Douglas Gregorfa047642009-02-04 00:32:51 +00001377 // Add direct and indirect base classes along with their associated
1378 // namespaces.
1379 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1380 Bases.push_back(Class);
1381 while (!Bases.empty()) {
1382 // Pop this class off the stack.
1383 Class = Bases.back();
1384 Bases.pop_back();
1385
1386 // Visit the base classes.
1387 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1388 BaseEnd = Class->bases_end();
1389 Base != BaseEnd; ++Base) {
Ted Kremenek5cad1f72009-07-17 01:20:38 +00001390 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
Douglas Gregorfa047642009-02-04 00:32:51 +00001391 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1392 if (AssociatedClasses.insert(BaseDecl)) {
1393 // Find the associated namespace for this base class.
1394 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1395 while (BaseCtx->isRecord())
1396 BaseCtx = BaseCtx->getParent();
Douglas Gregor69be8d62009-07-08 07:51:57 +00001397 if (NamespaceDecl *EnclosingNamespace
1398 = dyn_cast<NamespaceDecl>(BaseCtx))
Douglas Gregorfa047642009-02-04 00:32:51 +00001399 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001400 else if (BaseCtx->isTranslationUnit())
1401 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001402
1403 // Make sure we visit the bases of this base class.
1404 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1405 Bases.push_back(BaseDecl);
1406 }
1407 }
1408 }
1409}
1410
1411// \brief Add the associated classes and namespaces for
1412// argument-dependent lookup with an argument of type T
1413// (C++ [basic.lookup.koenig]p2).
1414static void
1415addAssociatedClassesAndNamespaces(QualType T,
1416 ASTContext &Context,
1417 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001418 Sema::AssociatedClassSet &AssociatedClasses,
1419 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001420 // C++ [basic.lookup.koenig]p2:
1421 //
1422 // For each argument type T in the function call, there is a set
1423 // of zero or more associated namespaces and a set of zero or more
1424 // associated classes to be considered. The sets of namespaces and
1425 // classes is determined entirely by the types of the function
1426 // arguments (and the namespace of any template template
1427 // argument). Typedef names and using-declarations used to specify
1428 // the types do not contribute to this set. The sets of namespaces
1429 // and classes are determined in the following way:
1430 T = Context.getCanonicalType(T).getUnqualifiedType();
1431
1432 // -- If T is a pointer to U or an array of U, its associated
1433 // namespaces and classes are those associated with U.
1434 //
1435 // We handle this by unwrapping pointer and array types immediately,
1436 // to avoid unnecessary recursion.
1437 while (true) {
Ted Kremenek1a1a6e22009-07-16 19:58:26 +00001438 if (const PointerType *Ptr = T->getAs<PointerType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001439 T = Ptr->getPointeeType();
1440 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1441 T = Ptr->getElementType();
1442 else
1443 break;
1444 }
1445
1446 // -- If T is a fundamental type, its associated sets of
1447 // namespaces and classes are both empty.
1448 if (T->getAsBuiltinType())
1449 return;
1450
1451 // -- If T is a class type (including unions), its associated
1452 // classes are: the class itself; the class of which it is a
1453 // member, if any; and its direct and indirect base
1454 // classes. Its associated namespaces are the namespaces in
1455 // which its associated classes are defined.
Ted Kremenek5cad1f72009-07-17 01:20:38 +00001456 if (const RecordType *ClassType = T->getAs<RecordType>())
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001457 if (CXXRecordDecl *ClassDecl
1458 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1459 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1460 AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001461 AssociatedClasses,
1462 GlobalScope);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001463 return;
1464 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001465
1466 // -- If T is an enumeration type, its associated namespace is
1467 // the namespace in which it is defined. If it is class
1468 // member, its associated class is the member’s class; else
1469 // it has no associated class.
1470 if (const EnumType *EnumT = T->getAsEnumType()) {
1471 EnumDecl *Enum = EnumT->getDecl();
1472
1473 DeclContext *Ctx = Enum->getDeclContext();
1474 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1475 AssociatedClasses.insert(EnclosingClass);
1476
1477 // Add the associated namespace for this class.
1478 while (Ctx->isRecord())
1479 Ctx = Ctx->getParent();
1480 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1481 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001482 else if (Ctx->isTranslationUnit())
1483 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001484
1485 return;
1486 }
1487
1488 // -- If T is a function type, its associated namespaces and
1489 // classes are those associated with the function parameter
1490 // types and those associated with the return type.
1491 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1492 // Return type
1493 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1494 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001495 AssociatedNamespaces, AssociatedClasses,
1496 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001497
Douglas Gregor72564e72009-02-26 23:50:07 +00001498 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001499 if (!Proto)
1500 return;
1501
1502 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001503 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001504 ArgEnd = Proto->arg_type_end();
1505 Arg != ArgEnd; ++Arg)
1506 addAssociatedClassesAndNamespaces(*Arg, Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001507 AssociatedNamespaces, AssociatedClasses,
1508 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001509
1510 return;
1511 }
1512
1513 // -- If T is a pointer to a member function of a class X, its
1514 // associated namespaces and classes are those associated
1515 // with the function parameter types and return type,
1516 // together with those associated with X.
1517 //
1518 // -- If T is a pointer to a data member of class X, its
1519 // associated namespaces and classes are those associated
1520 // with the member type together with those associated with
1521 // X.
Ted Kremenek5cad1f72009-07-17 01:20:38 +00001522 if (const MemberPointerType *MemberPtr = T->getAs<MemberPointerType>()) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001523 // Handle the type that the pointer to member points to.
1524 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1525 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001526 AssociatedNamespaces, AssociatedClasses,
1527 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001528
1529 // Handle the class type into which this points.
Ted Kremenek5cad1f72009-07-17 01:20:38 +00001530 if (const RecordType *Class = MemberPtr->getClass()->getAs<RecordType>())
Douglas Gregorfa047642009-02-04 00:32:51 +00001531 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1532 Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001533 AssociatedNamespaces, AssociatedClasses,
1534 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001535
1536 return;
1537 }
1538
1539 // FIXME: What about block pointers?
1540 // FIXME: What about Objective-C message sends?
1541}
1542
1543/// \brief Find the associated classes and namespaces for
1544/// argument-dependent lookup for a call with the given set of
1545/// arguments.
1546///
1547/// This routine computes the sets of associated classes and associated
1548/// namespaces searched by argument-dependent lookup
1549/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1550void
1551Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1552 AssociatedNamespaceSet &AssociatedNamespaces,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001553 AssociatedClassSet &AssociatedClasses,
1554 bool &GlobalScope) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001555 AssociatedNamespaces.clear();
1556 AssociatedClasses.clear();
1557
1558 // C++ [basic.lookup.koenig]p2:
1559 // For each argument type T in the function call, there is a set
1560 // of zero or more associated namespaces and a set of zero or more
1561 // associated classes to be considered. The sets of namespaces and
1562 // classes is determined entirely by the types of the function
1563 // arguments (and the namespace of any template template
1564 // argument).
1565 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1566 Expr *Arg = Args[ArgIdx];
1567
1568 if (Arg->getType() != Context.OverloadTy) {
1569 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001570 AssociatedNamespaces, AssociatedClasses,
1571 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001572 continue;
1573 }
1574
1575 // [...] In addition, if the argument is the name or address of a
1576 // set of overloaded functions and/or function templates, its
1577 // associated classes and namespaces are the union of those
1578 // associated with each of the members of the set: the namespace
1579 // in which the function or function template is defined and the
1580 // classes and namespaces associated with its (non-dependent)
1581 // parameter types and return type.
1582 DeclRefExpr *DRE = 0;
Douglas Gregordaa439a2009-07-08 10:57:20 +00001583 TemplateIdRefExpr *TIRE = 0;
1584 Arg = Arg->IgnoreParens();
Douglas Gregorfa047642009-02-04 00:32:51 +00001585 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregordaa439a2009-07-08 10:57:20 +00001586 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorfa047642009-02-04 00:32:51 +00001587 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
Douglas Gregordaa439a2009-07-08 10:57:20 +00001588 TIRE = dyn_cast<TemplateIdRefExpr>(unaryOp->getSubExpr());
1589 }
1590 } else {
Douglas Gregorfa047642009-02-04 00:32:51 +00001591 DRE = dyn_cast<DeclRefExpr>(Arg);
Douglas Gregordaa439a2009-07-08 10:57:20 +00001592 TIRE = dyn_cast<TemplateIdRefExpr>(Arg);
1593 }
1594
1595 OverloadedFunctionDecl *Ovl = 0;
1596 if (DRE)
1597 Ovl = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1598 else if (TIRE)
1599 Ovl = dyn_cast_or_null<OverloadedFunctionDecl>(
1600 TIRE->getTemplateName().getAsTemplateDecl());
Douglas Gregorfa047642009-02-04 00:32:51 +00001601 if (!Ovl)
1602 continue;
1603
1604 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1605 FuncEnd = Ovl->function_end();
1606 Func != FuncEnd; ++Func) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001607 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1608 if (!FDecl)
1609 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
Douglas Gregorfa047642009-02-04 00:32:51 +00001610
1611 // Add the namespace in which this function was defined. Note
1612 // that, if this is a member function, we do *not* consider the
1613 // enclosing namespace of its class.
1614 DeclContext *Ctx = FDecl->getDeclContext();
1615 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1616 AssociatedNamespaces.insert(EnclosingNamespace);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001617 else if (Ctx->isTranslationUnit())
1618 GlobalScope = true;
Douglas Gregorfa047642009-02-04 00:32:51 +00001619
1620 // Add the classes and namespaces associated with the parameter
1621 // types and return type of this function.
1622 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001623 AssociatedNamespaces, AssociatedClasses,
1624 GlobalScope);
Douglas Gregorfa047642009-02-04 00:32:51 +00001625 }
1626 }
1627}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001628
1629/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1630/// an acceptable non-member overloaded operator for a call whose
1631/// arguments have types T1 (and, if non-empty, T2). This routine
1632/// implements the check in C++ [over.match.oper]p3b2 concerning
1633/// enumeration types.
1634static bool
1635IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1636 QualType T1, QualType T2,
1637 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001638 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1639 return true;
1640
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001641 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1642 return true;
1643
1644 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1645 if (Proto->getNumArgs() < 1)
1646 return false;
1647
1648 if (T1->isEnumeralType()) {
1649 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1650 if (Context.getCanonicalType(T1).getUnqualifiedType()
1651 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1652 return true;
1653 }
1654
1655 if (Proto->getNumArgs() < 2)
1656 return false;
1657
1658 if (!T2.isNull() && T2->isEnumeralType()) {
1659 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1660 if (Context.getCanonicalType(T2).getUnqualifiedType()
1661 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1662 return true;
1663 }
1664
1665 return false;
1666}
1667
Douglas Gregor6e378de2009-04-23 23:18:26 +00001668/// \brief Find the protocol with the given name, if any.
1669ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001670 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
Douglas Gregor6e378de2009-04-23 23:18:26 +00001671 return cast_or_null<ObjCProtocolDecl>(D);
1672}
1673
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001674/// \brief Find the Objective-C implementation with the given name, if
1675/// any.
1676ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1677 Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1678 return cast_or_null<ObjCImplementationDecl>(D);
1679}
1680
1681/// \brief Find the Objective-C category implementation with the given
1682/// name, if any.
1683ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1684 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1685 return cast_or_null<ObjCCategoryImplDecl>(D);
1686}
1687
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001688void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1689 QualType T1, QualType T2,
1690 FunctionSet &Functions) {
1691 // C++ [over.match.oper]p3:
1692 // -- The set of non-member candidates is the result of the
1693 // unqualified lookup of operator@ in the context of the
1694 // expression according to the usual rules for name lookup in
1695 // unqualified function calls (3.4.2) except that all member
1696 // functions are ignored. However, if no operand has a class
1697 // type, only those non-member functions in the lookup set
1698 // that have a first parameter of type T1 or “reference to
1699 // (possibly cv-qualified) T1”, when T1 is an enumeration
1700 // type, or (if there is a right operand) a second parameter
1701 // of type T2 or “reference to (possibly cv-qualified) T2”,
1702 // when T2 is an enumeration type, are candidate functions.
1703 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1704 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1705
1706 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1707
1708 if (!Operators)
1709 return;
1710
1711 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1712 Op != OpEnd; ++Op) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001713 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op)) {
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001714 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1715 Functions.insert(FD); // FIXME: canonical FD
Douglas Gregor364e0212009-06-27 21:05:07 +00001716 } else if (FunctionTemplateDecl *FunTmpl
1717 = dyn_cast<FunctionTemplateDecl>(*Op)) {
1718 // FIXME: friend operators?
1719 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
1720 // later?
1721 if (!FunTmpl->getDeclContext()->isRecord())
1722 Functions.insert(FunTmpl);
1723 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001724 }
1725}
1726
1727void Sema::ArgumentDependentLookup(DeclarationName Name,
1728 Expr **Args, unsigned NumArgs,
1729 FunctionSet &Functions) {
1730 // Find all of the associated namespaces and classes based on the
1731 // arguments we have.
1732 AssociatedNamespaceSet AssociatedNamespaces;
1733 AssociatedClassSet AssociatedClasses;
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001734 bool GlobalScope = false;
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001735 FindAssociatedClassesAndNamespaces(Args, NumArgs,
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001736 AssociatedNamespaces, AssociatedClasses,
1737 GlobalScope);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001738
1739 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001740 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1741 // and let Y be the lookup set produced by argument dependent
1742 // lookup (defined as follows). If X contains [...] then Y is
1743 // empty. Otherwise Y is the set of declarations found in the
1744 // namespaces associated with the argument types as described
1745 // below. The set of declarations found by the lookup of the name
1746 // is the union of X and Y.
1747 //
1748 // Here, we compute Y and add its members to the overloaded
1749 // candidate set.
1750 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1751 NSEnd = AssociatedNamespaces.end();
1752 NS != NSEnd; ++NS) {
1753 // When considering an associated namespace, the lookup is the
1754 // same as the lookup performed when the associated namespace is
1755 // used as a qualifier (3.4.3.2) except that:
1756 //
1757 // -- Any using-directives in the associated namespace are
1758 // ignored.
1759 //
1760 // -- FIXME: Any namespace-scope friend functions declared in
1761 // associated classes are visible within their respective
1762 // namespaces even if they are not visible during an ordinary
1763 // lookup (11.4).
1764 DeclContext::lookup_iterator I, E;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001765 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001766 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*I))
1767 Functions.insert(Func);
1768 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*I))
1769 Functions.insert(FunTmpl);
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001770 }
1771 }
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001772
1773 if (GlobalScope) {
1774 DeclContext::lookup_iterator I, E;
1775 for (llvm::tie(I, E)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001776 = Context.getTranslationUnitDecl()->lookup(Name);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001777 I != E; ++I) {
Douglas Gregor364e0212009-06-27 21:05:07 +00001778 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*I))
1779 Functions.insert(Func);
1780 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(*I))
1781 Functions.insert(FunTmpl);
Douglas Gregor44bc2d52009-06-23 20:14:09 +00001782 }
1783 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001784}