1 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements name lookup for C, C++, Objective-C, and
13 //===----------------------------------------------------------------------===//
15 #include "SemaInherit.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/Parse/DeclSpec.h"
23 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallPtrSet.h"
33 using namespace clang;
35 typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
36 typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
37 typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
39 /// UsingDirAncestorCompare - Implements strict weak ordering of
40 /// UsingDirectives. It orders them by address of its common ancestor.
41 struct UsingDirAncestorCompare {
43 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
44 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
45 return U->getCommonAncestor() < Ctx;
48 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
49 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
50 return Ctx < U->getCommonAncestor();
53 /// @brief Compares UsingDirectiveDecl common ancestors.
54 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
55 return U1->getCommonAncestor() < U2->getCommonAncestor();
59 /// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
60 /// (ordered by common ancestors), found in namespace NS,
61 /// including all found (recursively) in their nominated namespaces.
62 void AddNamespaceUsingDirectives(ASTContext &Context,
64 UsingDirectivesTy &UDirs,
65 NamespaceSet &Visited) {
66 DeclContext::udir_iterator I, End;
68 for (llvm::tie(I, End) = NS->getUsingDirectives(Context); I !=End; ++I) {
70 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
71 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
72 if (Visited.insert(Nominated).second)
73 AddNamespaceUsingDirectives(Context, Nominated, UDirs, /*ref*/ Visited);
77 /// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
78 /// including all found in the namespaces they nominate.
79 static void AddScopeUsingDirectives(ASTContext &Context, Scope *S,
80 UsingDirectivesTy &UDirs) {
81 NamespaceSet VisitedNS;
83 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
85 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
88 AddNamespaceUsingDirectives(Context, Ctx, UDirs, /*ref*/ VisitedNS);
91 Scope::udir_iterator I = S->using_directives_begin(),
92 End = S->using_directives_end();
94 for (; I != End; ++I) {
95 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
97 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
99 NamespaceDecl *Nominated = UD->getNominatedNamespace();
100 if (!VisitedNS.count(Nominated)) {
101 VisitedNS.insert(Nominated);
102 AddNamespaceUsingDirectives(Context, Nominated, UDirs,
109 /// MaybeConstructOverloadSet - Name lookup has determined that the
110 /// elements in [I, IEnd) have the name that we are looking for, and
111 /// *I is a match for the namespace. This routine returns an
112 /// appropriate Decl for name lookup, which may either be *I or an
113 /// OverloadedFunctionDecl that represents the overloaded functions in
116 /// The existance of this routine is temporary; users of LookupResult
117 /// should be able to handle multiple results, to deal with cases of
118 /// ambiguity and overloaded functions without needing to create a
120 template<typename DeclIterator>
122 MaybeConstructOverloadSet(ASTContext &Context,
123 DeclIterator I, DeclIterator IEnd) {
124 assert(I != IEnd && "Iterator range cannot be empty");
125 assert(!isa<OverloadedFunctionDecl>(*I) &&
126 "Cannot have an overloaded function");
128 if ((*I)->isFunctionOrFunctionTemplate()) {
129 // If we found a function, there might be more functions. If
130 // so, collect them into an overload set.
131 DeclIterator Last = I;
132 OverloadedFunctionDecl *Ovl = 0;
134 Last != IEnd && (*Last)->isFunctionOrFunctionTemplate();
137 // FIXME: We leak this overload set. Eventually, we want to stop
138 // building the declarations for these overload sets, so there will be
140 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
141 (*I)->getDeclName());
142 NamedDecl *ND = (*I)->getUnderlyingDecl();
143 if (isa<FunctionDecl>(ND))
144 Ovl->addOverload(cast<FunctionDecl>(ND));
146 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
149 NamedDecl *ND = (*Last)->getUnderlyingDecl();
150 if (isa<FunctionDecl>(ND))
151 Ovl->addOverload(cast<FunctionDecl>(ND));
153 Ovl->addOverload(cast<FunctionTemplateDecl>(ND));
156 // If we had more than one function, we built an overload
165 /// Merges together multiple LookupResults dealing with duplicated Decl's.
166 static Sema::LookupResult
167 MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
168 typedef Sema::LookupResult LResult;
169 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
171 // Remove duplicated Decl pointing at same Decl, by storing them in
172 // associative collection. This might be case for code like:
174 // namespace A { int i; }
175 // namespace B { using namespace A; }
176 // namespace C { using namespace A; }
179 // using namespace B;
180 // using namespace C;
181 // ++i; // finds A::i, from both namespace B and C at global scope
184 // C++ [namespace.qual].p3:
185 // The same declaration found more than once is not an ambiguity
186 // (because it is still a unique declaration).
187 DeclsSetTy FoundDecls;
189 // Counter of tag names, and functions for resolving ambiguity
191 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
193 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
195 // No name lookup results, return early.
196 if (I == End) return LResult::CreateLookupResult(Context, 0);
198 // Keep track of the tag declaration we found. We only use this if
199 // we find a single tag declaration.
200 TagDecl *TagFound = 0;
202 for (; I != End; ++I) {
203 switch (I->getKind()) {
204 case LResult::NotFound:
206 "Should be always successful name lookup result here.");
209 case LResult::AmbiguousReference:
210 case LResult::AmbiguousBaseSubobjectTypes:
211 case LResult::AmbiguousBaseSubobjects:
212 assert(false && "Shouldn't get ambiguous lookup here.");
215 case LResult::Found: {
216 NamedDecl *ND = I->getAsDecl()->getUnderlyingDecl();
218 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
219 TagFound = Context.getCanonicalDecl(TD);
220 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
221 } else if (ND->isFunctionOrFunctionTemplate())
222 Functions += FoundDecls.insert(ND)? 1 : 0;
224 FoundDecls.insert(ND);
228 case LResult::FoundOverloaded:
229 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
230 Functions += FoundDecls.insert(*FI)? 1 : 0;
234 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
235 bool Ambiguous = false, NameHidesTags = false;
237 if (FoundDecls.size() == 1) {
238 // 1) Exactly one result.
239 } else if (TagNames > 1) {
240 // 2) Multiple tag names (even though they may be hidden by an
243 } else if (FoundDecls.size() - TagNames == 1) {
244 // 3) Ordinary name hides (optional) tag.
245 NameHidesTags = TagFound;
246 } else if (Functions) {
247 // C++ [basic.lookup].p1:
248 // ... Name lookup may associate more than one declaration with
249 // a name if it finds the name to be a function name; the declarations
250 // are said to form a set of overloaded functions (13.1).
251 // Overload resolution (13.3) takes place after name lookup has succeeded.
253 if (!OrdinaryNonFunc) {
254 // 4) Functions hide tag names.
255 NameHidesTags = TagFound;
257 // 5) Functions + ordinary names.
261 // 6) Multiple non-tag names
266 return LResult::CreateLookupResult(Context,
267 FoundDecls.begin(), FoundDecls.size());
269 // There's only one tag, TagFound. Remove it.
270 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
271 FoundDecls.erase(TagFound);
274 // Return successful name lookup result.
275 return LResult::CreateLookupResult(Context,
276 MaybeConstructOverloadSet(Context,
281 // Retrieve the set of identifier namespaces that correspond to a
282 // specific kind of name lookup.
284 getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
288 case Sema::LookupOrdinaryName:
289 case Sema::LookupOperatorName:
290 case Sema::LookupRedeclarationWithLinkage:
291 IDNS = Decl::IDNS_Ordinary;
293 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
296 case Sema::LookupTagName:
297 IDNS = Decl::IDNS_Tag;
300 case Sema::LookupMemberName:
301 IDNS = Decl::IDNS_Member;
303 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
306 case Sema::LookupNestedNameSpecifierName:
307 case Sema::LookupNamespaceName:
308 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
311 case Sema::LookupObjCProtocolName:
312 IDNS = Decl::IDNS_ObjCProtocol;
315 case Sema::LookupObjCImplementationName:
316 IDNS = Decl::IDNS_ObjCImplementation;
319 case Sema::LookupObjCCategoryImplName:
320 IDNS = Decl::IDNS_ObjCCategoryImpl;
327 Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
329 D = D->getUnderlyingDecl();
332 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
333 OverloadedDeclSingleDecl : SingleDecl;
334 Result.First = reinterpret_cast<uintptr_t>(D);
336 Result.Context = &Context;
340 /// @brief Moves the name-lookup results from Other to this LookupResult.
342 Sema::LookupResult::CreateLookupResult(ASTContext &Context,
343 IdentifierResolver::iterator F,
344 IdentifierResolver::iterator L) {
346 Result.Context = &Context;
348 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
349 IdentifierResolver::iterator Next = F;
351 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
352 Result.StoredKind = OverloadedDeclFromIdResolver;
353 Result.First = F.getAsOpaqueValue();
354 Result.Last = L.getAsOpaqueValue();
361 D = D->getUnderlyingDecl();
363 Result.StoredKind = SingleDecl;
364 Result.First = reinterpret_cast<uintptr_t>(D);
370 Sema::LookupResult::CreateLookupResult(ASTContext &Context,
371 DeclContext::lookup_iterator F,
372 DeclContext::lookup_iterator L) {
374 Result.Context = &Context;
376 if (F != L && (*F)->isFunctionOrFunctionTemplate()) {
377 DeclContext::lookup_iterator Next = F;
379 if (Next != L && (*Next)->isFunctionOrFunctionTemplate()) {
380 Result.StoredKind = OverloadedDeclFromDeclContext;
381 Result.First = reinterpret_cast<uintptr_t>(F);
382 Result.Last = reinterpret_cast<uintptr_t>(L);
389 D = D->getUnderlyingDecl();
391 Result.StoredKind = SingleDecl;
392 Result.First = reinterpret_cast<uintptr_t>(D);
397 /// @brief Determine the result of name lookup.
398 Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
399 switch (StoredKind) {
401 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
403 case OverloadedDeclSingleDecl:
404 case OverloadedDeclFromIdResolver:
405 case OverloadedDeclFromDeclContext:
406 return FoundOverloaded;
408 case AmbiguousLookupStoresBasePaths:
409 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
411 case AmbiguousLookupStoresDecls:
412 return AmbiguousReference;
415 // We can't ever get here.
419 /// @brief Converts the result of name lookup into a single (possible
420 /// NULL) pointer to a declaration.
422 /// The resulting declaration will either be the declaration we found
423 /// (if only a single declaration was found), an
424 /// OverloadedFunctionDecl (if an overloaded function was found), or
425 /// NULL (if no declaration was found). This conversion must not be
426 /// used anywhere where name lookup could result in an ambiguity.
428 /// The OverloadedFunctionDecl conversion is meant as a stop-gap
429 /// solution, since it causes the OverloadedFunctionDecl to be
430 /// leaked. FIXME: Eventually, there will be a better way to iterate
431 /// over the set of overloaded functions returned by name lookup.
432 NamedDecl *Sema::LookupResult::getAsDecl() const {
433 switch (StoredKind) {
435 return reinterpret_cast<NamedDecl *>(First);
437 case OverloadedDeclFromIdResolver:
438 return MaybeConstructOverloadSet(*Context,
439 IdentifierResolver::iterator::getFromOpaqueValue(First),
440 IdentifierResolver::iterator::getFromOpaqueValue(Last));
442 case OverloadedDeclFromDeclContext:
443 return MaybeConstructOverloadSet(*Context,
444 reinterpret_cast<DeclContext::lookup_iterator>(First),
445 reinterpret_cast<DeclContext::lookup_iterator>(Last));
447 case OverloadedDeclSingleDecl:
448 return reinterpret_cast<OverloadedFunctionDecl*>(First);
450 case AmbiguousLookupStoresDecls:
451 case AmbiguousLookupStoresBasePaths:
453 "Name lookup returned an ambiguity that could not be handled");
460 /// @brief Retrieves the BasePaths structure describing an ambiguous
461 /// name lookup, or null.
462 BasePaths *Sema::LookupResult::getBasePaths() const {
463 if (StoredKind == AmbiguousLookupStoresBasePaths)
464 return reinterpret_cast<BasePaths *>(First);
468 Sema::LookupResult::iterator::reference
469 Sema::LookupResult::iterator::operator*() const {
470 switch (Result->StoredKind) {
472 return reinterpret_cast<NamedDecl*>(Current);
474 case OverloadedDeclSingleDecl:
475 return *reinterpret_cast<NamedDecl**>(Current);
477 case OverloadedDeclFromIdResolver:
478 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
480 case AmbiguousLookupStoresBasePaths:
482 return *reinterpret_cast<NamedDecl**>(Current);
484 // Fall through to handle the DeclContext::lookup_iterator we're
487 case OverloadedDeclFromDeclContext:
488 case AmbiguousLookupStoresDecls:
489 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
495 Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
496 switch (Result->StoredKind) {
498 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
501 case OverloadedDeclSingleDecl: {
502 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
504 Current = reinterpret_cast<uintptr_t>(I);
508 case OverloadedDeclFromIdResolver: {
509 IdentifierResolver::iterator I
510 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
512 Current = I.getAsOpaqueValue();
516 case AmbiguousLookupStoresBasePaths:
518 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
520 Current = reinterpret_cast<uintptr_t>(I);
523 // Fall through to handle the DeclContext::lookup_iterator we're
526 case OverloadedDeclFromDeclContext:
527 case AmbiguousLookupStoresDecls: {
528 DeclContext::lookup_iterator I
529 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
531 Current = reinterpret_cast<uintptr_t>(I);
539 Sema::LookupResult::iterator Sema::LookupResult::begin() {
540 switch (StoredKind) {
542 case OverloadedDeclFromIdResolver:
543 case OverloadedDeclFromDeclContext:
544 case AmbiguousLookupStoresDecls:
545 return iterator(this, First);
547 case OverloadedDeclSingleDecl: {
548 OverloadedFunctionDecl * Ovl =
549 reinterpret_cast<OverloadedFunctionDecl*>(First);
550 return iterator(this,
551 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
554 case AmbiguousLookupStoresBasePaths:
556 return iterator(this,
557 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
559 return iterator(this,
560 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
563 // Required to suppress GCC warning.
567 Sema::LookupResult::iterator Sema::LookupResult::end() {
568 switch (StoredKind) {
570 case OverloadedDeclFromIdResolver:
571 case OverloadedDeclFromDeclContext:
572 case AmbiguousLookupStoresDecls:
573 return iterator(this, Last);
575 case OverloadedDeclSingleDecl: {
576 OverloadedFunctionDecl * Ovl =
577 reinterpret_cast<OverloadedFunctionDecl*>(First);
578 return iterator(this,
579 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
582 case AmbiguousLookupStoresBasePaths:
584 return iterator(this,
585 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
587 return iterator(this, reinterpret_cast<uintptr_t>(
588 getBasePaths()->front().Decls.second));
591 // Required to suppress GCC warning.
595 void Sema::LookupResult::Destroy() {
596 if (BasePaths *Paths = getBasePaths())
598 else if (getKind() == AmbiguousReference)
599 delete[] reinterpret_cast<NamedDecl **>(First);
603 CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
604 DeclarationName Name, Sema::LookupNameKind NameKind,
605 unsigned IDNS, LookupResultsTy &Results,
606 UsingDirectivesTy *UDirs = 0) {
608 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
610 // Perform qualified name lookup into the LookupCtx.
611 DeclContext::lookup_iterator I, E;
612 for (llvm::tie(I, E) = NS->lookup(Context, Name); I != E; ++I)
613 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
614 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
619 // For each UsingDirectiveDecl, which common ancestor is equal
620 // to NS, we preform qualified name lookup into namespace nominated by it.
621 UsingDirectivesTy::const_iterator UI, UEnd;
622 llvm::tie(UI, UEnd) =
623 std::equal_range(UDirs->begin(), UDirs->end(), NS,
624 UsingDirAncestorCompare());
626 for (; UI != UEnd; ++UI)
627 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
628 Name, NameKind, IDNS, Results);
632 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
633 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
634 return Ctx->isFileContext();
638 std::pair<bool, Sema::LookupResult>
639 Sema::CppLookupName(Scope *S, DeclarationName Name,
640 LookupNameKind NameKind, bool RedeclarationOnly) {
641 assert(getLangOptions().CPlusPlus &&
642 "Can perform only C++ lookup");
644 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
646 DeclContext *OutOfLineCtx = 0;
647 IdentifierResolver::iterator
648 I = IdResolver.begin(Name),
649 IEnd = IdResolver.end();
651 // First we lookup local scope.
652 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
653 // ...During unqualified name lookup (3.4.1), the names appear as if
654 // they were declared in the nearest enclosing namespace which contains
655 // both the using-directive and the nominated namespace.
656 // [Note: in this context, “contains” means “contains directly or
660 // namespace A { int i; }
664 // using namespace A;
665 // ++i; // finds local 'i', A::i appears at global scope
669 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
670 // Check whether the IdResolver has anything in this scope.
671 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
672 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
673 // We found something. Look for anything else in our scope
674 // with this same name and in an acceptable identifier
675 // namespace, so that we can construct an overload set if we
677 IdentifierResolver::iterator LastI = I;
678 for (++LastI; LastI != IEnd; ++LastI) {
679 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
682 LookupResult Result =
683 LookupResult::CreateLookupResult(Context, I, LastI);
684 return std::make_pair(true, Result);
687 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
689 // Perform member lookup into struct.
690 // FIXME: In some cases, we know that every name that could be found by
691 // this qualified name lookup will also be on the identifier chain. For
692 // example, inside a class without any base classes, we never need to
693 // perform qualified lookup because all of the members are on top of the
695 if (isa<RecordDecl>(Ctx)) {
696 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
698 return std::make_pair(true, R);
700 if (Ctx->getParent() != Ctx->getLexicalParent()
701 || isa<CXXMethodDecl>(Ctx)) {
702 // It is out of line defined C++ method or struct, we continue
703 // doing name lookup in parent context. Once we will find namespace
704 // or translation-unit we save it for possible checking
705 // using-directives later.
706 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
707 OutOfLineCtx = OutOfLineCtx->getParent()) {
708 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
710 return std::make_pair(true, R);
716 // Collect UsingDirectiveDecls in all scopes, and recursively all
717 // nominated namespaces by those using-directives.
718 // UsingDirectives are pushed to heap, in common ancestor pointer value order.
719 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
720 // don't build it for each lookup!
721 UsingDirectivesTy UDirs;
722 for (Scope *SC = Initial; SC; SC = SC->getParent())
723 if (SC->getFlags() & Scope::DeclScope)
724 AddScopeUsingDirectives(Context, SC, UDirs);
726 // Sort heapified UsingDirectiveDecls.
727 std::sort_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
729 // Lookup namespace scope, and global scope.
730 // Unqualified name lookup in C++ requires looking into scopes
731 // that aren't strictly lexical, and therefore we walk through the
732 // context as well as walking through the scopes.
734 LookupResultsTy LookupResults;
735 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
736 "We should have been looking only at file context here already.");
737 bool LookedInCtx = false;
739 while (OutOfLineCtx &&
740 OutOfLineCtx != S->getEntity() &&
741 OutOfLineCtx->isNamespace()) {
744 // Look into context considering using-directives.
745 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
746 LookupResults, &UDirs);
748 if ((Result = MergeLookupResults(Context, LookupResults)) ||
749 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
750 return std::make_pair(true, Result);
752 OutOfLineCtx = OutOfLineCtx->getParent();
755 for (; S; S = S->getParent()) {
756 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
757 assert(Ctx && Ctx->isFileContext() &&
758 "We should have been looking only at file context here already.");
760 // Check whether the IdResolver has anything in this scope.
761 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
762 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
763 // We found something. Look for anything else in our scope
764 // with this same name and in an acceptable identifier
765 // namespace, so that we can construct an overload set if we
767 IdentifierResolver::iterator LastI = I;
768 for (++LastI; LastI != IEnd; ++LastI) {
769 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
773 // We store name lookup result, and continue trying to look into
774 // associated context, and maybe namespaces nominated by
776 LookupResults.push_back(
777 LookupResult::CreateLookupResult(Context, I, LastI));
783 // Look into context considering using-directives.
784 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
785 LookupResults, &UDirs);
787 if ((Result = MergeLookupResults(Context, LookupResults)) ||
788 (RedeclarationOnly && !Ctx->isTransparentContext()))
789 return std::make_pair(true, Result);
792 if (!(LookedInCtx || LookupResults.empty())) {
793 // We didn't Performed lookup in Scope entity, so we return
794 // result form IdentifierResolver.
795 assert((LookupResults.size() == 1) && "Wrong size!");
796 return std::make_pair(true, LookupResults.front());
798 return std::make_pair(false, LookupResult());
801 /// @brief Perform unqualified name lookup starting from a given
804 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
805 /// used to find names within the current scope. For example, 'x' in
809 /// return x; // unqualified name look finds 'x' in the global scope
813 /// Different lookup criteria can find different names. For example, a
814 /// particular scope can have both a struct and a function of the same
815 /// name, and each can be found by certain lookup criteria. For more
816 /// information about lookup criteria, see the documentation for the
817 /// class LookupCriteria.
819 /// @param S The scope from which unqualified name lookup will
820 /// begin. If the lookup criteria permits, name lookup may also search
821 /// in the parent scopes.
823 /// @param Name The name of the entity that we are searching for.
825 /// @param Loc If provided, the source location where we're performing
826 /// name lookup. At present, this is only used to produce diagnostics when
827 /// C library functions (like "malloc") are implicitly declared.
829 /// @returns The result of name lookup, which includes zero or more
830 /// declarations and possibly additional information used to diagnose
833 Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
834 bool RedeclarationOnly, bool AllowBuiltinCreation,
835 SourceLocation Loc) {
836 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
838 if (!getLangOptions().CPlusPlus) {
839 // Unqualified name lookup in C/Objective-C is purely lexical, so
840 // search in the declarations attached to the name.
843 case Sema::LookupOrdinaryName:
844 IDNS = Decl::IDNS_Ordinary;
847 case Sema::LookupTagName:
848 IDNS = Decl::IDNS_Tag;
851 case Sema::LookupMemberName:
852 IDNS = Decl::IDNS_Member;
855 case Sema::LookupOperatorName:
856 case Sema::LookupNestedNameSpecifierName:
857 case Sema::LookupNamespaceName:
858 assert(false && "C does not perform these kinds of name lookup");
861 case Sema::LookupRedeclarationWithLinkage:
862 // Find the nearest non-transparent declaration scope.
863 while (!(S->getFlags() & Scope::DeclScope) ||
865 static_cast<DeclContext *>(S->getEntity())
866 ->isTransparentContext()))
868 IDNS = Decl::IDNS_Ordinary;
871 case Sema::LookupObjCProtocolName:
872 IDNS = Decl::IDNS_ObjCProtocol;
875 case Sema::LookupObjCImplementationName:
876 IDNS = Decl::IDNS_ObjCImplementation;
879 case Sema::LookupObjCCategoryImplName:
880 IDNS = Decl::IDNS_ObjCCategoryImpl;
884 // Scan up the scope chain looking for a decl that matches this
885 // identifier that is in the appropriate namespace. This search
886 // should not take long, as shadowing of names is uncommon, and
887 // deep shadowing is extremely uncommon.
888 bool LeftStartingScope = false;
890 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
891 IEnd = IdResolver.end();
893 if ((*I)->isInIdentifierNamespace(IDNS)) {
894 if (NameKind == LookupRedeclarationWithLinkage) {
895 // Determine whether this (or a previous) declaration is
897 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
898 LeftStartingScope = true;
900 // If we found something outside of our starting scope that
901 // does not have linkage, skip it.
902 if (LeftStartingScope && !((*I)->hasLinkage()))
906 if ((*I)->getAttr<OverloadableAttr>(Context)) {
907 // If this declaration has the "overloadable" attribute, we
908 // might have a set of overloaded functions.
910 // Figure out what scope the identifier is in.
911 while (!(S->getFlags() & Scope::DeclScope) ||
912 !S->isDeclScope(DeclPtrTy::make(*I)))
915 // Find the last declaration in this scope (with the same
917 IdentifierResolver::iterator LastI = I;
918 for (++LastI; LastI != IEnd; ++LastI) {
919 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
923 return LookupResult::CreateLookupResult(Context, I, LastI);
926 // We have a single lookup result.
927 return LookupResult::CreateLookupResult(Context, *I);
930 // Perform C++ unqualified name lookup.
931 std::pair<bool, LookupResult> MaybeResult =
932 CppLookupName(S, Name, NameKind, RedeclarationOnly);
933 if (MaybeResult.first)
934 return MaybeResult.second;
937 // If we didn't find a use of this identifier, and if the identifier
938 // corresponds to a compiler builtin, create the decl object for the builtin
939 // now, injecting it into translation unit scope, and return it.
940 if (NameKind == LookupOrdinaryName ||
941 NameKind == LookupRedeclarationWithLinkage) {
942 IdentifierInfo *II = Name.getAsIdentifierInfo();
943 if (II && AllowBuiltinCreation) {
944 // If this is a builtin on this (or all) targets, create the decl.
945 if (unsigned BuiltinID = II->getBuiltinID()) {
946 // In C++, we don't have any predefined library functions like
947 // 'malloc'. Instead, we'll just error.
948 if (getLangOptions().CPlusPlus &&
949 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
950 return LookupResult::CreateLookupResult(Context, 0);
952 return LookupResult::CreateLookupResult(Context,
953 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
954 S, RedeclarationOnly, Loc));
958 return LookupResult::CreateLookupResult(Context, 0);
961 /// @brief Perform qualified name lookup into a given context.
963 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
964 /// names when the context of those names is explicit specified, e.g.,
965 /// "std::vector" or "x->member".
967 /// Different lookup criteria can find different names. For example, a
968 /// particular scope can have both a struct and a function of the same
969 /// name, and each can be found by certain lookup criteria. For more
970 /// information about lookup criteria, see the documentation for the
971 /// class LookupCriteria.
973 /// @param LookupCtx The context in which qualified name lookup will
974 /// search. If the lookup criteria permits, name lookup may also search
975 /// in the parent contexts or (for C++ classes) base classes.
977 /// @param Name The name of the entity that we are searching for.
979 /// @param Criteria The criteria that this routine will use to
980 /// determine which names are visible and which names will be
981 /// found. Note that name lookup will find a name that is visible by
982 /// the given criteria, but the entity itself may not be semantically
983 /// correct or even the kind of entity expected based on the
984 /// lookup. For example, searching for a nested-name-specifier name
985 /// might result in an EnumDecl, which is visible but is not permitted
986 /// as a nested-name-specifier in C++03.
988 /// @returns The result of name lookup, which includes zero or more
989 /// declarations and possibly additional information used to diagnose
992 Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
993 LookupNameKind NameKind, bool RedeclarationOnly) {
994 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
996 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
998 // If we're performing qualified name lookup (e.g., lookup into a
999 // struct), find fields as part of ordinary name lookup.
1001 = getIdentifierNamespacesFromLookupNameKind(NameKind,
1002 getLangOptions().CPlusPlus);
1003 if (NameKind == LookupOrdinaryName)
1004 IDNS |= Decl::IDNS_Member;
1006 // Perform qualified name lookup into the LookupCtx.
1007 DeclContext::lookup_iterator I, E;
1008 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
1009 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1010 return LookupResult::CreateLookupResult(Context, I, E);
1012 // If this isn't a C++ class or we aren't allowed to look into base
1013 // classes, we're done.
1014 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
1015 return LookupResult::CreateLookupResult(Context, 0);
1017 // Perform lookup into our base classes.
1019 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
1021 // Look for this member in our base classes
1022 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
1023 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
1024 return LookupResult::CreateLookupResult(Context, 0);
1026 // C++ [class.member.lookup]p2:
1027 // [...] If the resulting set of declarations are not all from
1028 // sub-objects of the same type, or the set has a nonstatic member
1029 // and includes members from distinct sub-objects, there is an
1030 // ambiguity and the program is ill-formed. Otherwise that set is
1031 // the result of the lookup.
1032 // FIXME: support using declarations!
1033 QualType SubobjectType;
1034 int SubobjectNumber = 0;
1035 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1036 Path != PathEnd; ++Path) {
1037 const BasePathElement &PathElement = Path->back();
1039 // Determine whether we're looking at a distinct sub-object or not.
1040 if (SubobjectType.isNull()) {
1041 // This is the first subobject we've looked at. Record it's type.
1042 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1043 SubobjectNumber = PathElement.SubobjectNumber;
1044 } else if (SubobjectType
1045 != Context.getCanonicalType(PathElement.Base->getType())) {
1046 // We found members of the given name in two subobjects of
1047 // different types. This lookup is ambiguous.
1048 BasePaths *PathsOnHeap = new BasePaths;
1049 PathsOnHeap->swap(Paths);
1050 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
1051 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1052 // We have a different subobject of the same type.
1054 // C++ [class.member.lookup]p5:
1055 // A static member, a nested type or an enumerator defined in
1056 // a base class T can unambiguously be found even if an object
1057 // has more than one base class subobject of type T.
1058 Decl *FirstDecl = *Path->Decls.first;
1059 if (isa<VarDecl>(FirstDecl) ||
1060 isa<TypeDecl>(FirstDecl) ||
1061 isa<EnumConstantDecl>(FirstDecl))
1064 if (isa<CXXMethodDecl>(FirstDecl)) {
1065 // Determine whether all of the methods are static.
1066 bool AllMethodsAreStatic = true;
1067 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1068 Func != Path->Decls.second; ++Func) {
1069 if (!isa<CXXMethodDecl>(*Func)) {
1070 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1074 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1075 AllMethodsAreStatic = false;
1080 if (AllMethodsAreStatic)
1084 // We have found a nonstatic member name in multiple, distinct
1085 // subobjects. Name lookup is ambiguous.
1086 BasePaths *PathsOnHeap = new BasePaths;
1087 PathsOnHeap->swap(Paths);
1088 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
1092 // Lookup in a base class succeeded; return these results.
1094 // If we found a function declaration, return an overload set.
1095 if ((*Paths.front().Decls.first)->isFunctionOrFunctionTemplate())
1096 return LookupResult::CreateLookupResult(Context,
1097 Paths.front().Decls.first, Paths.front().Decls.second);
1099 // We found a non-function declaration; return a single declaration.
1100 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
1103 /// @brief Performs name lookup for a name that was parsed in the
1104 /// source code, and may contain a C++ scope specifier.
1106 /// This routine is a convenience routine meant to be called from
1107 /// contexts that receive a name and an optional C++ scope specifier
1108 /// (e.g., "N::M::x"). It will then perform either qualified or
1109 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1110 /// respectively) on the given name and return those results.
1112 /// @param S The scope from which unqualified name lookup will
1115 /// @param SS An optional C++ scope-specified, e.g., "::N::M".
1117 /// @param Name The name of the entity that name lookup will
1120 /// @param Loc If provided, the source location where we're performing
1121 /// name lookup. At present, this is only used to produce diagnostics when
1122 /// C library functions (like "malloc") are implicitly declared.
1124 /// @returns The result of qualified or unqualified name lookup.
1126 Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1127 DeclarationName Name, LookupNameKind NameKind,
1128 bool RedeclarationOnly, bool AllowBuiltinCreation,
1129 SourceLocation Loc) {
1130 if (SS && (SS->isSet() || SS->isInvalid())) {
1131 // If the scope specifier is invalid, don't even look for
1133 if (SS->isInvalid())
1134 return LookupResult::CreateLookupResult(Context, 0);
1136 assert(!isUnknownSpecialization(*SS) && "Can't lookup dependent types");
1138 if (isDependentScopeSpecifier(*SS)) {
1139 // Determine whether we are looking into the current
1141 NestedNameSpecifier *NNS
1142 = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1143 CXXRecordDecl *Current = getCurrentInstantiationOf(NNS);
1144 assert(Current && "Bad dependent scope specifier");
1146 // We nested name specifier refers to the current instantiation,
1147 // so now we will look for a member of the current instantiation
1148 // (C++0x [temp.dep.type]).
1149 unsigned IDNS = getIdentifierNamespacesFromLookupNameKind(NameKind, true);
1150 DeclContext::lookup_iterator I, E;
1151 for (llvm::tie(I, E) = Current->lookup(Context, Name); I != E; ++I)
1152 if (isAcceptableLookupResult(*I, NameKind, IDNS))
1153 return LookupResult::CreateLookupResult(Context, I, E);
1156 if (RequireCompleteDeclContext(*SS))
1157 return LookupResult::CreateLookupResult(Context, 0);
1159 return LookupQualifiedName(computeDeclContext(*SS),
1160 Name, NameKind, RedeclarationOnly);
1163 LookupResult result(LookupName(S, Name, NameKind, RedeclarationOnly,
1164 AllowBuiltinCreation, Loc));
1170 /// @brief Produce a diagnostic describing the ambiguity that resulted
1171 /// from name lookup.
1173 /// @param Result The ambiguous name lookup result.
1175 /// @param Name The name of the entity that name lookup was
1178 /// @param NameLoc The location of the name within the source code.
1180 /// @param LookupRange A source range that provides more
1181 /// source-location information concerning the lookup itself. For
1182 /// example, this range might highlight a nested-name-specifier that
1183 /// precedes the name.
1186 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1187 SourceLocation NameLoc,
1188 SourceRange LookupRange) {
1189 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1191 if (BasePaths *Paths = Result.getBasePaths()) {
1192 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1193 QualType SubobjectType = Paths->front().back().Base->getType();
1194 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1195 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1198 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1199 while (isa<CXXMethodDecl>(*Found) &&
1200 cast<CXXMethodDecl>(*Found)->isStatic())
1203 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1209 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1210 "Unhandled form of name lookup ambiguity");
1212 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1213 << Name << LookupRange;
1215 std::set<Decl *> DeclsPrinted;
1216 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1217 Path != PathEnd; ++Path) {
1218 Decl *D = *Path->Decls.first;
1219 if (DeclsPrinted.insert(D).second)
1220 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1225 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
1226 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1228 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
1229 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
1231 for (; DI != DEnd; ++DI)
1232 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1238 assert(false && "Unhandled form of name lookup ambiguity");
1240 // We can't reach here.
1244 // \brief Add the associated classes and namespaces for
1245 // argument-dependent lookup with an argument of class type
1246 // (C++ [basic.lookup.koenig]p2).
1248 addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1249 ASTContext &Context,
1250 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1251 Sema::AssociatedClassSet &AssociatedClasses,
1252 bool &GlobalScope) {
1253 // C++ [basic.lookup.koenig]p2:
1255 // -- If T is a class type (including unions), its associated
1256 // classes are: the class itself; the class of which it is a
1257 // member, if any; and its direct and indirect base
1258 // classes. Its associated namespaces are the namespaces in
1259 // which its associated classes are defined.
1261 // Add the class of which it is a member, if any.
1262 DeclContext *Ctx = Class->getDeclContext();
1263 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1264 AssociatedClasses.insert(EnclosingClass);
1265 // Add the associated namespace for this class.
1266 while (Ctx->isRecord())
1267 Ctx = Ctx->getParent();
1268 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1269 AssociatedNamespaces.insert(EnclosingNamespace);
1270 else if (Ctx->isTranslationUnit())
1273 // Add the class itself. If we've already seen this class, we don't
1274 // need to visit base classes.
1275 if (!AssociatedClasses.insert(Class))
1278 // FIXME: Handle class template specializations
1280 // Add direct and indirect base classes along with their associated
1282 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1283 Bases.push_back(Class);
1284 while (!Bases.empty()) {
1285 // Pop this class off the stack.
1286 Class = Bases.back();
1289 // Visit the base classes.
1290 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1291 BaseEnd = Class->bases_end();
1292 Base != BaseEnd; ++Base) {
1293 const RecordType *BaseType = Base->getType()->getAsRecordType();
1294 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1295 if (AssociatedClasses.insert(BaseDecl)) {
1296 // Find the associated namespace for this base class.
1297 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1298 while (BaseCtx->isRecord())
1299 BaseCtx = BaseCtx->getParent();
1300 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1301 AssociatedNamespaces.insert(EnclosingNamespace);
1302 else if (BaseCtx->isTranslationUnit())
1305 // Make sure we visit the bases of this base class.
1306 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1307 Bases.push_back(BaseDecl);
1313 // \brief Add the associated classes and namespaces for
1314 // argument-dependent lookup with an argument of type T
1315 // (C++ [basic.lookup.koenig]p2).
1317 addAssociatedClassesAndNamespaces(QualType T,
1318 ASTContext &Context,
1319 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1320 Sema::AssociatedClassSet &AssociatedClasses,
1321 bool &GlobalScope) {
1322 // C++ [basic.lookup.koenig]p2:
1324 // For each argument type T in the function call, there is a set
1325 // of zero or more associated namespaces and a set of zero or more
1326 // associated classes to be considered. The sets of namespaces and
1327 // classes is determined entirely by the types of the function
1328 // arguments (and the namespace of any template template
1329 // argument). Typedef names and using-declarations used to specify
1330 // the types do not contribute to this set. The sets of namespaces
1331 // and classes are determined in the following way:
1332 T = Context.getCanonicalType(T).getUnqualifiedType();
1334 // -- If T is a pointer to U or an array of U, its associated
1335 // namespaces and classes are those associated with U.
1337 // We handle this by unwrapping pointer and array types immediately,
1338 // to avoid unnecessary recursion.
1340 if (const PointerType *Ptr = T->getAsPointerType())
1341 T = Ptr->getPointeeType();
1342 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1343 T = Ptr->getElementType();
1348 // -- If T is a fundamental type, its associated sets of
1349 // namespaces and classes are both empty.
1350 if (T->getAsBuiltinType())
1353 // -- If T is a class type (including unions), its associated
1354 // classes are: the class itself; the class of which it is a
1355 // member, if any; and its direct and indirect base
1356 // classes. Its associated namespaces are the namespaces in
1357 // which its associated classes are defined.
1358 if (const RecordType *ClassType = T->getAsRecordType())
1359 if (CXXRecordDecl *ClassDecl
1360 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1361 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1362 AssociatedNamespaces,
1368 // -- If T is an enumeration type, its associated namespace is
1369 // the namespace in which it is defined. If it is class
1370 // member, its associated class is the member’s class; else
1371 // it has no associated class.
1372 if (const EnumType *EnumT = T->getAsEnumType()) {
1373 EnumDecl *Enum = EnumT->getDecl();
1375 DeclContext *Ctx = Enum->getDeclContext();
1376 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1377 AssociatedClasses.insert(EnclosingClass);
1379 // Add the associated namespace for this class.
1380 while (Ctx->isRecord())
1381 Ctx = Ctx->getParent();
1382 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1383 AssociatedNamespaces.insert(EnclosingNamespace);
1384 else if (Ctx->isTranslationUnit())
1390 // -- If T is a function type, its associated namespaces and
1391 // classes are those associated with the function parameter
1392 // types and those associated with the return type.
1393 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1395 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1397 AssociatedNamespaces, AssociatedClasses,
1400 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
1405 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1406 ArgEnd = Proto->arg_type_end();
1407 Arg != ArgEnd; ++Arg)
1408 addAssociatedClassesAndNamespaces(*Arg, Context,
1409 AssociatedNamespaces, AssociatedClasses,
1415 // -- If T is a pointer to a member function of a class X, its
1416 // associated namespaces and classes are those associated
1417 // with the function parameter types and return type,
1418 // together with those associated with X.
1420 // -- If T is a pointer to a data member of class X, its
1421 // associated namespaces and classes are those associated
1422 // with the member type together with those associated with
1424 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1425 // Handle the type that the pointer to member points to.
1426 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1428 AssociatedNamespaces, AssociatedClasses,
1431 // Handle the class type into which this points.
1432 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1433 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1435 AssociatedNamespaces, AssociatedClasses,
1441 // FIXME: What about block pointers?
1442 // FIXME: What about Objective-C message sends?
1445 /// \brief Find the associated classes and namespaces for
1446 /// argument-dependent lookup for a call with the given set of
1449 /// This routine computes the sets of associated classes and associated
1450 /// namespaces searched by argument-dependent lookup
1451 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1453 Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1454 AssociatedNamespaceSet &AssociatedNamespaces,
1455 AssociatedClassSet &AssociatedClasses,
1456 bool &GlobalScope) {
1457 AssociatedNamespaces.clear();
1458 AssociatedClasses.clear();
1460 // C++ [basic.lookup.koenig]p2:
1461 // For each argument type T in the function call, there is a set
1462 // of zero or more associated namespaces and a set of zero or more
1463 // associated classes to be considered. The sets of namespaces and
1464 // classes is determined entirely by the types of the function
1465 // arguments (and the namespace of any template template
1467 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1468 Expr *Arg = Args[ArgIdx];
1470 if (Arg->getType() != Context.OverloadTy) {
1471 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1472 AssociatedNamespaces, AssociatedClasses,
1477 // [...] In addition, if the argument is the name or address of a
1478 // set of overloaded functions and/or function templates, its
1479 // associated classes and namespaces are the union of those
1480 // associated with each of the members of the set: the namespace
1481 // in which the function or function template is defined and the
1482 // classes and namespaces associated with its (non-dependent)
1483 // parameter types and return type.
1484 DeclRefExpr *DRE = 0;
1485 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1486 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1487 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1489 DRE = dyn_cast<DeclRefExpr>(Arg);
1493 OverloadedFunctionDecl *Ovl
1494 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1498 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1499 FuncEnd = Ovl->function_end();
1500 Func != FuncEnd; ++Func) {
1501 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*Func);
1503 FDecl = cast<FunctionTemplateDecl>(*Func)->getTemplatedDecl();
1505 // Add the namespace in which this function was defined. Note
1506 // that, if this is a member function, we do *not* consider the
1507 // enclosing namespace of its class.
1508 DeclContext *Ctx = FDecl->getDeclContext();
1509 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1510 AssociatedNamespaces.insert(EnclosingNamespace);
1511 else if (Ctx->isTranslationUnit())
1514 // Add the classes and namespaces associated with the parameter
1515 // types and return type of this function.
1516 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1517 AssociatedNamespaces, AssociatedClasses,
1523 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1524 /// an acceptable non-member overloaded operator for a call whose
1525 /// arguments have types T1 (and, if non-empty, T2). This routine
1526 /// implements the check in C++ [over.match.oper]p3b2 concerning
1527 /// enumeration types.
1529 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1530 QualType T1, QualType T2,
1531 ASTContext &Context) {
1532 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1535 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1538 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1539 if (Proto->getNumArgs() < 1)
1542 if (T1->isEnumeralType()) {
1543 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1544 if (Context.getCanonicalType(T1).getUnqualifiedType()
1545 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1549 if (Proto->getNumArgs() < 2)
1552 if (!T2.isNull() && T2->isEnumeralType()) {
1553 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1554 if (Context.getCanonicalType(T2).getUnqualifiedType()
1555 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1562 /// \brief Find the protocol with the given name, if any.
1563 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II) {
1564 Decl *D = LookupName(TUScope, II, LookupObjCProtocolName).getAsDecl();
1565 return cast_or_null<ObjCProtocolDecl>(D);
1568 /// \brief Find the Objective-C implementation with the given name, if
1570 ObjCImplementationDecl *Sema::LookupObjCImplementation(IdentifierInfo *II) {
1571 Decl *D = LookupName(TUScope, II, LookupObjCImplementationName).getAsDecl();
1572 return cast_or_null<ObjCImplementationDecl>(D);
1575 /// \brief Find the Objective-C category implementation with the given
1577 ObjCCategoryImplDecl *Sema::LookupObjCCategoryImpl(IdentifierInfo *II) {
1578 Decl *D = LookupName(TUScope, II, LookupObjCCategoryImplName).getAsDecl();
1579 return cast_or_null<ObjCCategoryImplDecl>(D);
1582 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1583 QualType T1, QualType T2,
1584 FunctionSet &Functions) {
1585 // C++ [over.match.oper]p3:
1586 // -- The set of non-member candidates is the result of the
1587 // unqualified lookup of operator@ in the context of the
1588 // expression according to the usual rules for name lookup in
1589 // unqualified function calls (3.4.2) except that all member
1590 // functions are ignored. However, if no operand has a class
1591 // type, only those non-member functions in the lookup set
1592 // that have a first parameter of type T1 or “reference to
1593 // (possibly cv-qualified) T1”, when T1 is an enumeration
1594 // type, or (if there is a right operand) a second parameter
1595 // of type T2 or “reference to (possibly cv-qualified) T2”,
1596 // when T2 is an enumeration type, are candidate functions.
1597 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1598 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1600 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1605 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1606 Op != OpEnd; ++Op) {
1607 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1608 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1609 Functions.insert(FD); // FIXME: canonical FD
1613 void Sema::ArgumentDependentLookup(DeclarationName Name,
1614 Expr **Args, unsigned NumArgs,
1615 FunctionSet &Functions) {
1616 // Find all of the associated namespaces and classes based on the
1617 // arguments we have.
1618 AssociatedNamespaceSet AssociatedNamespaces;
1619 AssociatedClassSet AssociatedClasses;
1620 bool GlobalScope = false;
1621 FindAssociatedClassesAndNamespaces(Args, NumArgs,
1622 AssociatedNamespaces, AssociatedClasses,
1625 // C++ [basic.lookup.argdep]p3:
1626 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1627 // and let Y be the lookup set produced by argument dependent
1628 // lookup (defined as follows). If X contains [...] then Y is
1629 // empty. Otherwise Y is the set of declarations found in the
1630 // namespaces associated with the argument types as described
1631 // below. The set of declarations found by the lookup of the name
1632 // is the union of X and Y.
1634 // Here, we compute Y and add its members to the overloaded
1636 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1637 NSEnd = AssociatedNamespaces.end();
1638 NS != NSEnd; ++NS) {
1639 // When considering an associated namespace, the lookup is the
1640 // same as the lookup performed when the associated namespace is
1641 // used as a qualifier (3.4.3.2) except that:
1643 // -- Any using-directives in the associated namespace are
1646 // -- FIXME: Any namespace-scope friend functions declared in
1647 // associated classes are visible within their respective
1648 // namespaces even if they are not visible during an ordinary
1650 DeclContext::lookup_iterator I, E;
1651 for (llvm::tie(I, E) = (*NS)->lookup(Context, Name); I != E; ++I) {
1652 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1656 Functions.insert(Func);
1661 DeclContext::lookup_iterator I, E;
1662 for (llvm::tie(I, E)
1663 = Context.getTranslationUnitDecl()->lookup(Context, Name);
1665 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1669 Functions.insert(Func);