blob: a9ec3f2faf61ab8824f1445a12f8b7d703e45907 [file] [log] [blame]
Douglas Gregor78d70132009-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"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20#include "llvm/ADT/STLExtras.h"
21
22using namespace clang;
23
24/// MaybeConstructOverloadSet - Name lookup has determined that the
25/// elements in [I, IEnd) have the name that we are looking for, and
26/// *I is a match for the namespace. This routine returns an
27/// appropriate Decl for name lookup, which may either be *I or an
28/// OverloadeFunctionDecl that represents the overloaded functions in
29/// [I, IEnd).
30///
31/// The existance of this routine is temporary; LookupDecl should
32/// probably be able to return multiple results, to deal with cases of
33/// ambiguity and overloaded functions without needing to create a
34/// Decl node.
35template<typename DeclIterator>
36static Decl *
37MaybeConstructOverloadSet(ASTContext &Context,
38 DeclIterator I, DeclIterator IEnd) {
39 assert(I != IEnd && "Iterator range cannot be empty");
40 assert(!isa<OverloadedFunctionDecl>(*I) &&
41 "Cannot have an overloaded function");
42
43 if (isa<FunctionDecl>(*I)) {
44 // If we found a function, there might be more functions. If
45 // so, collect them into an overload set.
46 DeclIterator Last = I;
47 OverloadedFunctionDecl *Ovl = 0;
48 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
49 if (!Ovl) {
50 // FIXME: We leak this overload set. Eventually, we want to
51 // stop building the declarations for these overload sets, so
52 // there will be nothing to leak.
53 Ovl = OverloadedFunctionDecl::Create(Context,
54 cast<ScopedDecl>(*I)->getDeclContext(),
55 (*I)->getDeclName());
56 Ovl->addOverload(cast<FunctionDecl>(*I));
57 }
58 Ovl->addOverload(cast<FunctionDecl>(*Last));
59 }
60
61 // If we had more than one function, we built an overload
62 // set. Return it.
63 if (Ovl)
64 return Ovl;
65 }
66
67 return *I;
68}
69
70/// @brief Constructs name lookup criteria.
71///
72/// @param K The kind of name that we're searching for.
73///
74/// @param RedeclarationOnly If true, then name lookup will only look
75/// into the current scope for names, not in parent scopes. This
76/// option should be set when we're looking to introduce a new
77/// declaration into scope.
78///
79/// @param CPlusPlus Whether we are performing C++ name lookup or not.
80Sema::LookupCriteria::LookupCriteria(NameKind K, bool RedeclarationOnly,
81 bool CPlusPlus)
82 : Kind(K), AllowLazyBuiltinCreation(K == Ordinary),
83 RedeclarationOnly(RedeclarationOnly) {
84 switch (Kind) {
85 case Ordinary:
86 IDNS = Decl::IDNS_Ordinary;
87 if (CPlusPlus)
88 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
89 break;
90
91 case Tag:
92 IDNS = Decl::IDNS_Tag;
93 break;
94
95 case Member:
96 IDNS = Decl::IDNS_Member;
97 if (CPlusPlus)
98 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
99 break;
100
101 case NestedNameSpecifier:
102 case Namespace:
103 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
104 break;
105 }
106}
107
108/// isLookupResult - Determines whether D is a suitable lookup result
109/// according to the lookup criteria.
110bool Sema::LookupCriteria::isLookupResult(Decl *D) const {
111 switch (Kind) {
112 case Ordinary:
113 case Tag:
114 case Member:
115 return D->isInIdentifierNamespace(IDNS);
116
117 case NestedNameSpecifier:
118 return isa<TypedefDecl>(D) || D->isInIdentifierNamespace(Decl::IDNS_Tag);
119
120 case Namespace:
121 return isa<NamespaceDecl>(D);
122 }
123
124 assert(false && "isLookupResult always returns before this point");
125 return false;
126}
127
128/// @brief Determine the result of name lookup.
129Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
130 switch (StoredKind) {
131 case SingleDecl:
132 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
133
134 case OverloadedDeclFromIdResolver:
135 case OverloadedDeclFromDeclContext:
136 return FoundOverloaded;
137
138 case AmbiguousLookup:
139 return Ambiguous;
140 }
141
142 // We can't get here, but GCC complains nonetheless.
143 return Ambiguous;
144}
145
146/// @brief Converts the result of name lookup into a single (possible
147/// NULL) pointer to a declaration.
148///
149/// The resulting declaration will either be the declaration we found
150/// (if only a single declaration was found), an
151/// OverloadedFunctionDecl (if an overloaded function was found), or
152/// NULL (if no declaration was found). This conversion must not be
153/// used anywhere where name lookup could result in an ambiguity.
154///
155/// The OverloadedFunctionDecl conversion is meant as a stop-gap
156/// solution, since it causes the OverloadedFunctionDecl to be
157/// leaked. FIXME: Eventually, there will be a better way to iterate
158/// over the set of overloaded functions returned by name lookup.
159Decl *Sema::LookupResult::getAsDecl() const {
160 switch (StoredKind) {
161 case SingleDecl:
162 return reinterpret_cast<Decl *>(First);
163
164 case OverloadedDeclFromIdResolver:
165 return MaybeConstructOverloadSet(*Context,
166 IdentifierResolver::iterator::getFromOpaqueValue(First),
167 IdentifierResolver::iterator::getFromOpaqueValue(Last));
168
169 case OverloadedDeclFromDeclContext:
170 return MaybeConstructOverloadSet(*Context,
171 reinterpret_cast<DeclContext::lookup_iterator>(First),
172 reinterpret_cast<DeclContext::lookup_iterator>(Last));
173
174 case AmbiguousLookup:
175 assert(false &&
176 "Name lookup returned an ambiguity that could not be handled");
177 break;
178 }
179
180 return 0;
181}
182
183/// @brief Perform unqualified name lookup starting from a given
184/// scope.
185///
186/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
187/// used to find names within the current scope. For example, 'x' in
188/// @code
189/// int x;
190/// int f() {
191/// return x; // unqualified name look finds 'x' in the global scope
192/// }
193/// @endcode
194///
195/// Different lookup criteria can find different names. For example, a
196/// particular scope can have both a struct and a function of the same
197/// name, and each can be found by certain lookup criteria. For more
198/// information about lookup criteria, see the documentation for the
199/// class LookupCriteria.
200///
201/// @param S The scope from which unqualified name lookup will
202/// begin. If the lookup criteria permits, name lookup may also search
203/// in the parent scopes.
204///
205/// @param Name The name of the entity that we are searching for.
206///
207/// @param Criteria The criteria that this routine will use to
208/// determine which names are visible and which names will be
209/// found. Note that name lookup will find a name that is visible by
210/// the given criteria, but the entity itself may not be semantically
211/// correct or even the kind of entity expected based on the
212/// lookup. For example, searching for a nested-name-specifier name
213/// might result in an EnumDecl, which is visible but is not permitted
214/// as a nested-name-specifier in C++03.
215///
216/// @returns The result of name lookup, which includes zero or more
217/// declarations and possibly additional information used to diagnose
218/// ambiguities.
219Sema::LookupResult
220Sema::LookupName(Scope *S, DeclarationName Name, LookupCriteria Criteria) {
221 if (!Name) return LookupResult(Context, 0);
222
223 if (!getLangOptions().CPlusPlus) {
224 // Unqualified name lookup in C/Objective-C is purely lexical, so
225 // search in the declarations attached to the name.
226
227 // For the purposes of unqualified name lookup, structs and unions
228 // don't have scopes at all. For example:
229 //
230 // struct X {
231 // struct T { int i; } x;
232 // };
233 //
234 // void f() {
235 // struct T t; // okay: T is defined lexically within X, but
236 // // semantically at global scope
237 // };
238 //
239 // FIXME: Is there a better way to deal with this?
240 DeclContext *SearchCtx = CurContext;
241 while (isa<RecordDecl>(SearchCtx) || isa<EnumDecl>(SearchCtx))
242 SearchCtx = SearchCtx->getParent();
243 IdentifierResolver::iterator I
244 = IdResolver.begin(Name, SearchCtx, !Criteria.RedeclarationOnly);
245
246 // Scan up the scope chain looking for a decl that matches this
247 // identifier that is in the appropriate namespace. This search
248 // should not take long, as shadowing of names is uncommon, and
249 // deep shadowing is extremely uncommon.
250 for (; I != IdResolver.end(); ++I)
251 if (Criteria.isLookupResult(*I))
252 return LookupResult(Context, *I);
253 } else {
254 // Unqualified name lookup in C++ requires looking into scopes
255 // that aren't strictly lexical, and therefore we walk through the
256 // context as well as walking through the scopes.
257
258 // FIXME: does "true" for LookInParentCtx actually make sense?
259 IdentifierResolver::iterator
260 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
261 IEnd = IdResolver.end();
262 for (; S; S = S->getParent()) {
263 // Check whether the IdResolver has anything in this scope.
264 for (; I != IEnd && S->isDeclScope(*I); ++I) {
265 if (Criteria.isLookupResult(*I)) {
266 // We found something. Look for anything else in our scope
267 // with this same name and in an acceptable identifier
268 // namespace, so that we can construct an overload set if we
269 // need to.
270 IdentifierResolver::iterator LastI = I;
271 for (++LastI; LastI != IEnd; ++LastI) {
272 if (!S->isDeclScope(*LastI))
273 break;
274 }
275 return LookupResult(Context, I, LastI);
276 }
277 }
278
279 // If there is an entity associated with this scope, it's a
280 // DeclContext. We might need to perform qualified lookup into
281 // it.
282 // FIXME: We're performing redundant lookups here, where the
283 // scope stack mirrors the semantic nested of classes and
284 // namespaces. We can save some work by checking the lexical
285 // scope against the semantic scope and avoiding any lookups
286 // when they are the same.
287 // FIXME: In some cases, we know that every name that could be
288 // found by this qualified name lookup will also be on the
289 // identifier chain. For example, inside a class without any
290 // base classes, we never need to perform qualified lookup
291 // because all of the members are on top of the identifier
292 // chain. However, we cannot perform this optimization when the
293 // lexical and semantic scopes don't line up, e.g., in an
294 // out-of-line member definition.
295 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
296 while (Ctx && Ctx->isFunctionOrMethod())
297 Ctx = Ctx->getParent();
298 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
299 // Look for declarations of this name in this scope.
300 if (LookupResult Result = LookupQualifiedName(Ctx, Name, Criteria))
301 return Result;
302
303 if (Criteria.RedeclarationOnly && !Ctx->isTransparentContext())
304 return LookupResult(Context, 0);
305
306 Ctx = Ctx->getParent();
307 }
308 }
309 }
310
311 // If we didn't find a use of this identifier, and if the identifier
312 // corresponds to a compiler builtin, create the decl object for the builtin
313 // now, injecting it into translation unit scope, and return it.
314 if (Criteria.Kind == LookupCriteria::Ordinary) {
315 IdentifierInfo *II = Name.getAsIdentifierInfo();
316 if (Criteria.AllowLazyBuiltinCreation && II) {
317 // If this is a builtin on this (or all) targets, create the decl.
318 if (unsigned BuiltinID = II->getBuiltinID())
319 return LookupResult(Context,
320 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
321 S));
322 }
323 if (getLangOptions().ObjC1 && II) {
324 // @interface and @compatibility_alias introduce typedef-like names.
325 // Unlike typedef's, they can only be introduced at file-scope (and are
326 // therefore not scoped decls). They can, however, be shadowed by
327 // other names in IDNS_Ordinary.
328 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
329 if (IDI != ObjCInterfaceDecls.end())
330 return LookupResult(Context, IDI->second);
331 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
332 if (I != ObjCAliasDecls.end())
333 return LookupResult(Context, I->second->getClassInterface());
334 }
335 }
336 return LookupResult(Context, 0);
337}
338
339/// @brief Perform qualified name lookup into a given context.
340///
341/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
342/// names when the context of those names is explicit specified, e.g.,
343/// "std::vector" or "x->member".
344///
345/// Different lookup criteria can find different names. For example, a
346/// particular scope can have both a struct and a function of the same
347/// name, and each can be found by certain lookup criteria. For more
348/// information about lookup criteria, see the documentation for the
349/// class LookupCriteria.
350///
351/// @param LookupCtx The context in which qualified name lookup will
352/// search. If the lookup criteria permits, name lookup may also search
353/// in the parent contexts or (for C++ classes) base classes.
354///
355/// @param Name The name of the entity that we are searching for.
356///
357/// @param Criteria The criteria that this routine will use to
358/// determine which names are visible and which names will be
359/// found. Note that name lookup will find a name that is visible by
360/// the given criteria, but the entity itself may not be semantically
361/// correct or even the kind of entity expected based on the
362/// lookup. For example, searching for a nested-name-specifier name
363/// might result in an EnumDecl, which is visible but is not permitted
364/// as a nested-name-specifier in C++03.
365///
366/// @returns The result of name lookup, which includes zero or more
367/// declarations and possibly additional information used to diagnose
368/// ambiguities.
369Sema::LookupResult
370Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
371 LookupCriteria Criteria) {
372 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
373
374 if (!Name) return LookupResult(Context, 0);
375
376 // If we're performing qualified name lookup (e.g., lookup into a
377 // struct), find fields as part of ordinary name lookup.
378 if (Criteria.Kind == LookupCriteria::Ordinary)
379 Criteria.IDNS |= Decl::IDNS_Member;
380
381 // Perform qualified name lookup into the LookupCtx.
382 // FIXME: Will need to look into base classes and such.
383 DeclContext::lookup_iterator I, E;
384 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
385 if (Criteria.isLookupResult(*I))
386 return LookupResult(Context, I, E);
387
388 return LookupResult(Context, 0);
389}
390
391/// @brief Performs name lookup for a name that was parsed in the
392/// source code, and may contain a C++ scope specifier.
393///
394/// This routine is a convenience routine meant to be called from
395/// contexts that receive a name and an optional C++ scope specifier
396/// (e.g., "N::M::x"). It will then perform either qualified or
397/// unqualified name lookup (with LookupQualifiedName or LookupName,
398/// respectively) on the given name and return those results.
399///
400/// @param S The scope from which unqualified name lookup will
401/// begin.
402///
403/// @param SS An optional C++ scope-specified, e.g., "::N::M".
404///
405/// @param Name The name of the entity that name lookup will
406/// search for.
407///
408/// @param Criteria The criteria that will determine which entities
409/// are visible to name lookup.
410///
411/// @returns The result of qualified or unqualified name lookup.
412Sema::LookupResult
413Sema::LookupParsedName(Scope *S, const CXXScopeSpec &SS,
414 DeclarationName Name, LookupCriteria Criteria) {
415 if (SS.isSet())
416 return LookupQualifiedName(static_cast<DeclContext *>(SS.getScopeRep()),
417 Name, Criteria);
418
419 return LookupName(S, Name, Criteria);
420}
421
422