blob: b85824382bf4162f7a6c57d42da53a29a4f57419 [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"
Douglas Gregor29dfa2f2009-01-15 00:26:24 +000015#include "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregor78d70132009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Basic/LangOptions.h"
22#include "llvm/ADT/STLExtras.h"
23
24using namespace clang;
25
26/// MaybeConstructOverloadSet - Name lookup has determined that the
27/// elements in [I, IEnd) have the name that we are looking for, and
28/// *I is a match for the namespace. This routine returns an
29/// appropriate Decl for name lookup, which may either be *I or an
30/// OverloadeFunctionDecl that represents the overloaded functions in
31/// [I, IEnd).
32///
33/// The existance of this routine is temporary; LookupDecl should
34/// probably be able to return multiple results, to deal with cases of
35/// ambiguity and overloaded functions without needing to create a
36/// Decl node.
37template<typename DeclIterator>
38static Decl *
39MaybeConstructOverloadSet(ASTContext &Context,
40 DeclIterator I, DeclIterator IEnd) {
41 assert(I != IEnd && "Iterator range cannot be empty");
42 assert(!isa<OverloadedFunctionDecl>(*I) &&
43 "Cannot have an overloaded function");
44
45 if (isa<FunctionDecl>(*I)) {
46 // If we found a function, there might be more functions. If
47 // so, collect them into an overload set.
48 DeclIterator Last = I;
49 OverloadedFunctionDecl *Ovl = 0;
50 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
51 if (!Ovl) {
52 // FIXME: We leak this overload set. Eventually, we want to
53 // stop building the declarations for these overload sets, so
54 // there will be nothing to leak.
55 Ovl = OverloadedFunctionDecl::Create(Context,
56 cast<ScopedDecl>(*I)->getDeclContext(),
57 (*I)->getDeclName());
58 Ovl->addOverload(cast<FunctionDecl>(*I));
59 }
60 Ovl->addOverload(cast<FunctionDecl>(*Last));
61 }
62
63 // If we had more than one function, we built an overload
64 // set. Return it.
65 if (Ovl)
66 return Ovl;
67 }
68
69 return *I;
70}
71
72/// @brief Constructs name lookup criteria.
73///
74/// @param K The kind of name that we're searching for.
75///
76/// @param RedeclarationOnly If true, then name lookup will only look
77/// into the current scope for names, not in parent scopes. This
78/// option should be set when we're looking to introduce a new
79/// declaration into scope.
80///
81/// @param CPlusPlus Whether we are performing C++ name lookup or not.
82Sema::LookupCriteria::LookupCriteria(NameKind K, bool RedeclarationOnly,
83 bool CPlusPlus)
84 : Kind(K), AllowLazyBuiltinCreation(K == Ordinary),
85 RedeclarationOnly(RedeclarationOnly) {
86 switch (Kind) {
87 case Ordinary:
88 IDNS = Decl::IDNS_Ordinary;
89 if (CPlusPlus)
90 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
91 break;
92
93 case Tag:
94 IDNS = Decl::IDNS_Tag;
95 break;
96
97 case Member:
98 IDNS = Decl::IDNS_Member;
99 if (CPlusPlus)
100 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
101 break;
102
103 case NestedNameSpecifier:
104 case Namespace:
105 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
106 break;
107 }
108}
109
110/// isLookupResult - Determines whether D is a suitable lookup result
111/// according to the lookup criteria.
112bool Sema::LookupCriteria::isLookupResult(Decl *D) const {
113 switch (Kind) {
114 case Ordinary:
115 case Tag:
116 case Member:
117 return D->isInIdentifierNamespace(IDNS);
118
119 case NestedNameSpecifier:
120 return isa<TypedefDecl>(D) || D->isInIdentifierNamespace(Decl::IDNS_Tag);
121
122 case Namespace:
123 return isa<NamespaceDecl>(D);
124 }
125
126 assert(false && "isLookupResult always returns before this point");
127 return false;
128}
129
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000130Sema::LookupResult::LookupResult(ASTContext &Context,
131 IdentifierResolver::iterator F,
132 IdentifierResolver::iterator L)
133 : Context(&Context) {
134 if (F != L && isa<FunctionDecl>(*F)) {
135 IdentifierResolver::iterator Next = F;
136 ++Next;
137 if (Next != L && isa<FunctionDecl>(*Next)) {
138 StoredKind = OverloadedDeclFromIdResolver;
139 First = F.getAsOpaqueValue();
140 Last = L.getAsOpaqueValue();
141 return;
142 }
143 }
144
145 StoredKind = SingleDecl;
146 First = reinterpret_cast<uintptr_t>(*F);
147 Last = 0;
148}
149
150Sema::LookupResult::LookupResult(ASTContext &Context,
151 DeclContext::lookup_iterator F,
152 DeclContext::lookup_iterator L)
153 : Context(&Context) {
154 if (F != L && isa<FunctionDecl>(*F)) {
155 DeclContext::lookup_iterator Next = F;
156 ++Next;
157 if (Next != L && isa<FunctionDecl>(*Next)) {
158 StoredKind = OverloadedDeclFromDeclContext;
159 First = reinterpret_cast<uintptr_t>(F);
160 Last = reinterpret_cast<uintptr_t>(L);
161 return;
162 }
163 }
164
165 StoredKind = SingleDecl;
166 First = reinterpret_cast<uintptr_t>(*F);
167 Last = 0;
168}
169
Douglas Gregor78d70132009-01-14 22:20:51 +0000170/// @brief Determine the result of name lookup.
171Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
172 switch (StoredKind) {
173 case SingleDecl:
174 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
175
176 case OverloadedDeclFromIdResolver:
177 case OverloadedDeclFromDeclContext:
178 return FoundOverloaded;
179
180 case AmbiguousLookup:
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000181 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor78d70132009-01-14 22:20:51 +0000182 }
183
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000184 // We can't ever get here.
185 return NotFound;
Douglas Gregor78d70132009-01-14 22:20:51 +0000186}
187
188/// @brief Converts the result of name lookup into a single (possible
189/// NULL) pointer to a declaration.
190///
191/// The resulting declaration will either be the declaration we found
192/// (if only a single declaration was found), an
193/// OverloadedFunctionDecl (if an overloaded function was found), or
194/// NULL (if no declaration was found). This conversion must not be
195/// used anywhere where name lookup could result in an ambiguity.
196///
197/// The OverloadedFunctionDecl conversion is meant as a stop-gap
198/// solution, since it causes the OverloadedFunctionDecl to be
199/// leaked. FIXME: Eventually, there will be a better way to iterate
200/// over the set of overloaded functions returned by name lookup.
201Decl *Sema::LookupResult::getAsDecl() const {
202 switch (StoredKind) {
203 case SingleDecl:
204 return reinterpret_cast<Decl *>(First);
205
206 case OverloadedDeclFromIdResolver:
207 return MaybeConstructOverloadSet(*Context,
208 IdentifierResolver::iterator::getFromOpaqueValue(First),
209 IdentifierResolver::iterator::getFromOpaqueValue(Last));
210
211 case OverloadedDeclFromDeclContext:
212 return MaybeConstructOverloadSet(*Context,
213 reinterpret_cast<DeclContext::lookup_iterator>(First),
214 reinterpret_cast<DeclContext::lookup_iterator>(Last));
215
216 case AmbiguousLookup:
217 assert(false &&
218 "Name lookup returned an ambiguity that could not be handled");
219 break;
220 }
221
222 return 0;
223}
224
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000225/// @brief Retrieves the BasePaths structure describing an ambiguous
226/// name lookup.
227BasePaths *Sema::LookupResult::getBasePaths() const {
228 assert((StoredKind == AmbiguousLookup) &&
229 "getBasePaths can only be used on an ambiguous lookup");
230 return reinterpret_cast<BasePaths *>(First);
231}
232
Douglas Gregor78d70132009-01-14 22:20:51 +0000233/// @brief Perform unqualified name lookup starting from a given
234/// scope.
235///
236/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
237/// used to find names within the current scope. For example, 'x' in
238/// @code
239/// int x;
240/// int f() {
241/// return x; // unqualified name look finds 'x' in the global scope
242/// }
243/// @endcode
244///
245/// Different lookup criteria can find different names. For example, a
246/// particular scope can have both a struct and a function of the same
247/// name, and each can be found by certain lookup criteria. For more
248/// information about lookup criteria, see the documentation for the
249/// class LookupCriteria.
250///
251/// @param S The scope from which unqualified name lookup will
252/// begin. If the lookup criteria permits, name lookup may also search
253/// in the parent scopes.
254///
255/// @param Name The name of the entity that we are searching for.
256///
257/// @param Criteria The criteria that this routine will use to
258/// determine which names are visible and which names will be
259/// found. Note that name lookup will find a name that is visible by
260/// the given criteria, but the entity itself may not be semantically
261/// correct or even the kind of entity expected based on the
262/// lookup. For example, searching for a nested-name-specifier name
263/// might result in an EnumDecl, which is visible but is not permitted
264/// as a nested-name-specifier in C++03.
265///
266/// @returns The result of name lookup, which includes zero or more
267/// declarations and possibly additional information used to diagnose
268/// ambiguities.
269Sema::LookupResult
270Sema::LookupName(Scope *S, DeclarationName Name, LookupCriteria Criteria) {
271 if (!Name) return LookupResult(Context, 0);
272
273 if (!getLangOptions().CPlusPlus) {
274 // Unqualified name lookup in C/Objective-C is purely lexical, so
275 // search in the declarations attached to the name.
276
277 // For the purposes of unqualified name lookup, structs and unions
278 // don't have scopes at all. For example:
279 //
280 // struct X {
281 // struct T { int i; } x;
282 // };
283 //
284 // void f() {
285 // struct T t; // okay: T is defined lexically within X, but
286 // // semantically at global scope
287 // };
288 //
289 // FIXME: Is there a better way to deal with this?
290 DeclContext *SearchCtx = CurContext;
291 while (isa<RecordDecl>(SearchCtx) || isa<EnumDecl>(SearchCtx))
292 SearchCtx = SearchCtx->getParent();
293 IdentifierResolver::iterator I
294 = IdResolver.begin(Name, SearchCtx, !Criteria.RedeclarationOnly);
295
296 // Scan up the scope chain looking for a decl that matches this
297 // identifier that is in the appropriate namespace. This search
298 // should not take long, as shadowing of names is uncommon, and
299 // deep shadowing is extremely uncommon.
300 for (; I != IdResolver.end(); ++I)
301 if (Criteria.isLookupResult(*I))
302 return LookupResult(Context, *I);
303 } else {
304 // Unqualified name lookup in C++ requires looking into scopes
305 // that aren't strictly lexical, and therefore we walk through the
306 // context as well as walking through the scopes.
307
308 // FIXME: does "true" for LookInParentCtx actually make sense?
309 IdentifierResolver::iterator
310 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
311 IEnd = IdResolver.end();
312 for (; S; S = S->getParent()) {
313 // Check whether the IdResolver has anything in this scope.
314 for (; I != IEnd && S->isDeclScope(*I); ++I) {
315 if (Criteria.isLookupResult(*I)) {
316 // We found something. Look for anything else in our scope
317 // with this same name and in an acceptable identifier
318 // namespace, so that we can construct an overload set if we
319 // need to.
320 IdentifierResolver::iterator LastI = I;
321 for (++LastI; LastI != IEnd; ++LastI) {
322 if (!S->isDeclScope(*LastI))
323 break;
324 }
325 return LookupResult(Context, I, LastI);
326 }
327 }
328
329 // If there is an entity associated with this scope, it's a
330 // DeclContext. We might need to perform qualified lookup into
331 // it.
332 // FIXME: We're performing redundant lookups here, where the
333 // scope stack mirrors the semantic nested of classes and
334 // namespaces. We can save some work by checking the lexical
335 // scope against the semantic scope and avoiding any lookups
336 // when they are the same.
337 // FIXME: In some cases, we know that every name that could be
338 // found by this qualified name lookup will also be on the
339 // identifier chain. For example, inside a class without any
340 // base classes, we never need to perform qualified lookup
341 // because all of the members are on top of the identifier
342 // chain. However, we cannot perform this optimization when the
343 // lexical and semantic scopes don't line up, e.g., in an
344 // out-of-line member definition.
345 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
346 while (Ctx && Ctx->isFunctionOrMethod())
347 Ctx = Ctx->getParent();
348 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
349 // Look for declarations of this name in this scope.
350 if (LookupResult Result = LookupQualifiedName(Ctx, Name, Criteria))
351 return Result;
352
353 if (Criteria.RedeclarationOnly && !Ctx->isTransparentContext())
354 return LookupResult(Context, 0);
355
356 Ctx = Ctx->getParent();
357 }
358 }
359 }
360
361 // If we didn't find a use of this identifier, and if the identifier
362 // corresponds to a compiler builtin, create the decl object for the builtin
363 // now, injecting it into translation unit scope, and return it.
364 if (Criteria.Kind == LookupCriteria::Ordinary) {
365 IdentifierInfo *II = Name.getAsIdentifierInfo();
366 if (Criteria.AllowLazyBuiltinCreation && II) {
367 // If this is a builtin on this (or all) targets, create the decl.
368 if (unsigned BuiltinID = II->getBuiltinID())
369 return LookupResult(Context,
370 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
371 S));
372 }
373 if (getLangOptions().ObjC1 && II) {
374 // @interface and @compatibility_alias introduce typedef-like names.
375 // Unlike typedef's, they can only be introduced at file-scope (and are
376 // therefore not scoped decls). They can, however, be shadowed by
377 // other names in IDNS_Ordinary.
378 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
379 if (IDI != ObjCInterfaceDecls.end())
380 return LookupResult(Context, IDI->second);
381 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
382 if (I != ObjCAliasDecls.end())
383 return LookupResult(Context, I->second->getClassInterface());
384 }
385 }
386 return LookupResult(Context, 0);
387}
388
389/// @brief Perform qualified name lookup into a given context.
390///
391/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
392/// names when the context of those names is explicit specified, e.g.,
393/// "std::vector" or "x->member".
394///
395/// Different lookup criteria can find different names. For example, a
396/// particular scope can have both a struct and a function of the same
397/// name, and each can be found by certain lookup criteria. For more
398/// information about lookup criteria, see the documentation for the
399/// class LookupCriteria.
400///
401/// @param LookupCtx The context in which qualified name lookup will
402/// search. If the lookup criteria permits, name lookup may also search
403/// in the parent contexts or (for C++ classes) base classes.
404///
405/// @param Name The name of the entity that we are searching for.
406///
407/// @param Criteria The criteria that this routine will use to
408/// determine which names are visible and which names will be
409/// found. Note that name lookup will find a name that is visible by
410/// the given criteria, but the entity itself may not be semantically
411/// correct or even the kind of entity expected based on the
412/// lookup. For example, searching for a nested-name-specifier name
413/// might result in an EnumDecl, which is visible but is not permitted
414/// as a nested-name-specifier in C++03.
415///
416/// @returns The result of name lookup, which includes zero or more
417/// declarations and possibly additional information used to diagnose
418/// ambiguities.
419Sema::LookupResult
420Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
421 LookupCriteria Criteria) {
422 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
423
424 if (!Name) return LookupResult(Context, 0);
425
426 // If we're performing qualified name lookup (e.g., lookup into a
427 // struct), find fields as part of ordinary name lookup.
428 if (Criteria.Kind == LookupCriteria::Ordinary)
429 Criteria.IDNS |= Decl::IDNS_Member;
430
431 // Perform qualified name lookup into the LookupCtx.
Douglas Gregor78d70132009-01-14 22:20:51 +0000432 DeclContext::lookup_iterator I, E;
433 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
434 if (Criteria.isLookupResult(*I))
435 return LookupResult(Context, I, E);
436
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000437 // If this isn't a C++ class or we aren't allowed to look into base
438 // classes, we're done.
439 if (Criteria.RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
440 return LookupResult(Context, 0);
441
442 // Perform lookup into our base classes.
443 BasePaths Paths;
444
445 // Look for this member in our base classes
446 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
447 MemberLookupCriteria(Name, Criteria), Paths))
448 return LookupResult(Context, 0);
449
450 // C++ [class.member.lookup]p2:
451 // [...] If the resulting set of declarations are not all from
452 // sub-objects of the same type, or the set has a nonstatic member
453 // and includes members from distinct sub-objects, there is an
454 // ambiguity and the program is ill-formed. Otherwise that set is
455 // the result of the lookup.
456 // FIXME: support using declarations!
457 QualType SubobjectType;
458 int SubobjectNumber;
459 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
460 Path != PathEnd; ++Path) {
461 const BasePathElement &PathElement = Path->back();
462
463 // Determine whether we're looking at a distinct sub-object or not.
464 if (SubobjectType.isNull()) {
465 // This is the first subobject we've looked at. Record it's type.
466 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
467 SubobjectNumber = PathElement.SubobjectNumber;
468 } else if (SubobjectType
469 != Context.getCanonicalType(PathElement.Base->getType())) {
470 // We found members of the given name in two subobjects of
471 // different types. This lookup is ambiguous.
472 BasePaths *PathsOnHeap = new BasePaths;
473 PathsOnHeap->swap(Paths);
474 return LookupResult(Context, PathsOnHeap, true);
475 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
476 // We have a different subobject of the same type.
477
478 // C++ [class.member.lookup]p5:
479 // A static member, a nested type or an enumerator defined in
480 // a base class T can unambiguously be found even if an object
481 // has more than one base class subobject of type T.
482 ScopedDecl *FirstDecl = *Path->Decls.first;
483 if (isa<VarDecl>(FirstDecl) ||
484 isa<TypeDecl>(FirstDecl) ||
485 isa<EnumConstantDecl>(FirstDecl))
486 continue;
487
488 if (isa<CXXMethodDecl>(FirstDecl)) {
489 // Determine whether all of the methods are static.
490 bool AllMethodsAreStatic = true;
491 for (DeclContext::lookup_iterator Func = Path->Decls.first;
492 Func != Path->Decls.second; ++Func) {
493 if (!isa<CXXMethodDecl>(*Func)) {
494 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
495 break;
496 }
497
498 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
499 AllMethodsAreStatic = false;
500 break;
501 }
502 }
503
504 if (AllMethodsAreStatic)
505 continue;
506 }
507
508 // We have found a nonstatic member name in multiple, distinct
509 // subobjects. Name lookup is ambiguous.
510 BasePaths *PathsOnHeap = new BasePaths;
511 PathsOnHeap->swap(Paths);
512 return LookupResult(Context, PathsOnHeap, false);
513 }
514 }
515
516 // Lookup in a base class succeeded; return these results.
517
518 // If we found a function declaration, return an overload set.
519 if (isa<FunctionDecl>(*Paths.front().Decls.first))
520 return LookupResult(Context,
521 Paths.front().Decls.first, Paths.front().Decls.second);
522
523 // We found a non-function declaration; return a single declaration.
524 return LookupResult(Context, *Paths.front().Decls.first);
Douglas Gregor78d70132009-01-14 22:20:51 +0000525}
526
527/// @brief Performs name lookup for a name that was parsed in the
528/// source code, and may contain a C++ scope specifier.
529///
530/// This routine is a convenience routine meant to be called from
531/// contexts that receive a name and an optional C++ scope specifier
532/// (e.g., "N::M::x"). It will then perform either qualified or
533/// unqualified name lookup (with LookupQualifiedName or LookupName,
534/// respectively) on the given name and return those results.
535///
536/// @param S The scope from which unqualified name lookup will
537/// begin.
538///
539/// @param SS An optional C++ scope-specified, e.g., "::N::M".
540///
541/// @param Name The name of the entity that name lookup will
542/// search for.
543///
544/// @param Criteria The criteria that will determine which entities
545/// are visible to name lookup.
546///
547/// @returns The result of qualified or unqualified name lookup.
548Sema::LookupResult
549Sema::LookupParsedName(Scope *S, const CXXScopeSpec &SS,
550 DeclarationName Name, LookupCriteria Criteria) {
551 if (SS.isSet())
552 return LookupQualifiedName(static_cast<DeclContext *>(SS.getScopeRep()),
553 Name, Criteria);
554
555 return LookupName(S, Name, Criteria);
556}
557
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000558/// @brief Produce a diagnostic describing the ambiguity that resulted
559/// from name lookup.
560///
561/// @param Result The ambiguous name lookup result.
562///
563/// @param Name The name of the entity that name lookup was
564/// searching for.
565///
566/// @param NameLoc The location of the name within the source code.
567///
568/// @param LookupRange A source range that provides more
569/// source-location information concerning the lookup itself. For
570/// example, this range might highlight a nested-name-specifier that
571/// precedes the name.
572///
573/// @returns true
574bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
575 SourceLocation NameLoc,
576 SourceRange LookupRange) {
577 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
578
579 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
580 BasePaths *Paths = Result.getBasePaths();
581 QualType SubobjectType = Paths->front().back().Base->getType();
582 return Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
583 << Name << SubobjectType << LookupRange;
584 }
585
586 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
587 "Unhandled form of name lookup ambiguity");
588
589 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
590 << Name << LookupRange;
591
592 // FIXME: point out the members we found using notes.
593 return true;
594}
Douglas Gregor78d70132009-01-14 22:20:51 +0000595