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 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/Sema.h"
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/DeclSpec.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Sema/TemplateDeduction.h"
21 #include "clang/Sema/ExternalSemaSource.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExprCXX.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/Support/ErrorHandling.h"
45 using namespace clang;
49 class UnqualUsingEntry {
50 const DeclContext *Nominated;
51 const DeclContext *CommonAncestor;
54 UnqualUsingEntry(const DeclContext *Nominated,
55 const DeclContext *CommonAncestor)
56 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
59 const DeclContext *getCommonAncestor() const {
60 return CommonAncestor;
63 const DeclContext *getNominatedNamespace() const {
67 // Sort by the pointer value of the common ancestor.
69 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
70 return L.getCommonAncestor() < R.getCommonAncestor();
73 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
74 return E.getCommonAncestor() < DC;
77 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
78 return DC < E.getCommonAncestor();
83 /// A collection of using directives, as used by C++ unqualified
85 class UnqualUsingDirectiveSet {
86 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
89 llvm::SmallPtrSet<DeclContext*, 8> visited;
92 UnqualUsingDirectiveSet() {}
94 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
95 // C++ [namespace.udir]p1:
96 // During unqualified name lookup, the names appear as if they
97 // were declared in the nearest enclosing namespace which contains
98 // both the using-directive and the nominated namespace.
99 DeclContext *InnermostFileDC
100 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
101 assert(InnermostFileDC && InnermostFileDC->isFileContext());
103 for (; S; S = S->getParent()) {
104 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
105 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
106 visit(Ctx, EffectiveDC);
108 Scope::udir_iterator I = S->using_directives_begin(),
109 End = S->using_directives_end();
111 for (; I != End; ++I)
112 visit(*I, InnermostFileDC);
117 // Visits a context and collect all of its using directives
118 // recursively. Treats all using directives as if they were
119 // declared in the context.
121 // A given context is only every visited once, so it is important
122 // that contexts be visited from the inside out in order to get
123 // the effective DCs right.
124 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
125 if (!visited.insert(DC))
128 addUsingDirectives(DC, EffectiveDC);
131 // Visits a using directive and collects all of its using
132 // directives recursively. Treats all using directives as if they
133 // were declared in the effective DC.
134 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
135 DeclContext *NS = UD->getNominatedNamespace();
136 if (!visited.insert(NS))
139 addUsingDirective(UD, EffectiveDC);
140 addUsingDirectives(NS, EffectiveDC);
143 // Adds all the using directives in a context (and those nominated
144 // by its using directives, transitively) as if they appeared in
145 // the given effective context.
146 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
147 llvm::SmallVector<DeclContext*,4> queue;
149 DeclContext::udir_iterator I, End;
150 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
151 UsingDirectiveDecl *UD = *I;
152 DeclContext *NS = UD->getNominatedNamespace();
153 if (visited.insert(NS)) {
154 addUsingDirective(UD, EffectiveDC);
167 // Add a using directive as if it had been declared in the given
168 // context. This helps implement C++ [namespace.udir]p3:
169 // The using-directive is transitive: if a scope contains a
170 // using-directive that nominates a second namespace that itself
171 // contains using-directives, the effect is as if the
172 // using-directives from the second namespace also appeared in
174 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
175 // Find the common ancestor between the effective context and
176 // the nominated namespace.
177 DeclContext *Common = UD->getNominatedNamespace();
178 while (!Common->Encloses(EffectiveDC))
179 Common = Common->getParent();
180 Common = Common->getPrimaryContext();
182 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
186 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
189 typedef ListTy::const_iterator const_iterator;
191 const_iterator begin() const { return list.begin(); }
192 const_iterator end() const { return list.end(); }
194 std::pair<const_iterator,const_iterator>
195 getNamespacesFor(DeclContext *DC) const {
196 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
197 UnqualUsingEntry::Comparator());
202 // Retrieve the set of identifier namespaces that correspond to a
203 // specific kind of name lookup.
204 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
206 bool Redeclaration) {
209 case Sema::LookupOrdinaryName:
210 case Sema::LookupRedeclarationWithLinkage:
211 IDNS = Decl::IDNS_Ordinary;
213 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
215 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
219 case Sema::LookupOperatorName:
220 // Operator lookup is its own crazy thing; it is not the same
221 // as (e.g.) looking up an operator name for redeclaration.
222 assert(!Redeclaration && "cannot do redeclaration operator lookup");
223 IDNS = Decl::IDNS_NonMemberOperator;
226 case Sema::LookupTagName:
228 IDNS = Decl::IDNS_Type;
230 // When looking for a redeclaration of a tag name, we add:
231 // 1) TagFriend to find undeclared friend decls
232 // 2) Namespace because they can't "overload" with tag decls.
233 // 3) Tag because it includes class templates, which can't
234 // "overload" with tag decls.
236 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
238 IDNS = Decl::IDNS_Tag;
241 case Sema::LookupLabel:
242 IDNS = Decl::IDNS_Label;
245 case Sema::LookupMemberName:
246 IDNS = Decl::IDNS_Member;
248 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
251 case Sema::LookupNestedNameSpecifierName:
252 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
255 case Sema::LookupNamespaceName:
256 IDNS = Decl::IDNS_Namespace;
259 case Sema::LookupUsingDeclName:
260 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
261 | Decl::IDNS_Member | Decl::IDNS_Using;
264 case Sema::LookupObjCProtocolName:
265 IDNS = Decl::IDNS_ObjCProtocol;
268 case Sema::LookupAnyName:
269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
270 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
277 void LookupResult::configure() {
278 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
279 isForRedeclaration());
281 // If we're looking for one of the allocation or deallocation
282 // operators, make sure that the implicitly-declared new and delete
283 // operators can be found.
284 if (!isForRedeclaration()) {
285 switch (NameInfo.getName().getCXXOverloadedOperator()) {
289 case OO_Array_Delete:
290 SemaRef.DeclareGlobalNewDelete();
299 void LookupResult::sanity() const {
300 assert(ResultKind != NotFound || Decls.size() == 0);
301 assert(ResultKind != Found || Decls.size() == 1);
302 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
303 (Decls.size() == 1 &&
304 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
305 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
306 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
307 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
308 Ambiguity == AmbiguousBaseSubobjectTypes)));
309 assert((Paths != NULL) == (ResultKind == Ambiguous &&
310 (Ambiguity == AmbiguousBaseSubobjectTypes ||
311 Ambiguity == AmbiguousBaseSubobjects)));
314 // Necessary because CXXBasePaths is not complete in Sema.h
315 void LookupResult::deletePaths(CXXBasePaths *Paths) {
319 /// Resolves the result kind of this lookup.
320 void LookupResult::resolveKind() {
321 unsigned N = Decls.size();
323 // Fast case: no possible ambiguity.
325 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
329 // If there's a single decl, we need to examine it to decide what
330 // kind of lookup this is.
332 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
333 if (isa<FunctionTemplateDecl>(D))
334 ResultKind = FoundOverloaded;
335 else if (isa<UnresolvedUsingValueDecl>(D))
336 ResultKind = FoundUnresolvedValue;
340 // Don't do any extra resolution if we've already resolved as ambiguous.
341 if (ResultKind == Ambiguous) return;
343 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
344 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
346 bool Ambiguous = false;
347 bool HasTag = false, HasFunction = false, HasNonFunction = false;
348 bool HasFunctionTemplate = false, HasUnresolved = false;
350 unsigned UniqueTagIndex = 0;
354 NamedDecl *D = Decls[I]->getUnderlyingDecl();
355 D = cast<NamedDecl>(D->getCanonicalDecl());
357 // Redeclarations of types via typedef can occur both within a scope
358 // and, through using declarations and directives, across scopes. There is
359 // no ambiguity if they all refer to the same type, so unique based on the
361 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
362 if (!TD->getDeclContext()->isRecord()) {
363 QualType T = SemaRef.Context.getTypeDeclType(TD);
364 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
365 // The type is not unique; pull something off the back and continue
367 Decls[I] = Decls[--N];
373 if (!Unique.insert(D)) {
374 // If it's not unique, pull something off the back (and
375 // continue at this index).
376 Decls[I] = Decls[--N];
380 // Otherwise, do some decl type analysis and then continue.
382 if (isa<UnresolvedUsingValueDecl>(D)) {
383 HasUnresolved = true;
384 } else if (isa<TagDecl>(D)) {
389 } else if (isa<FunctionTemplateDecl>(D)) {
391 HasFunctionTemplate = true;
392 } else if (isa<FunctionDecl>(D)) {
397 HasNonFunction = true;
402 // C++ [basic.scope.hiding]p2:
403 // A class name or enumeration name can be hidden by the name of
404 // an object, function, or enumerator declared in the same
405 // scope. If a class or enumeration name and an object, function,
406 // or enumerator are declared in the same scope (in any order)
407 // with the same name, the class or enumeration name is hidden
408 // wherever the object, function, or enumerator name is visible.
409 // But it's still an error if there are distinct tag types found,
410 // even if they're not visible. (ref?)
411 if (HideTags && HasTag && !Ambiguous &&
412 (HasFunction || HasNonFunction || HasUnresolved)) {
413 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
414 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
415 Decls[UniqueTagIndex] = Decls[--N];
422 if (HasNonFunction && (HasFunction || HasUnresolved))
426 setAmbiguous(LookupResult::AmbiguousReference);
427 else if (HasUnresolved)
428 ResultKind = LookupResult::FoundUnresolvedValue;
429 else if (N > 1 || HasFunctionTemplate)
430 ResultKind = LookupResult::FoundOverloaded;
432 ResultKind = LookupResult::Found;
435 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
436 CXXBasePaths::const_paths_iterator I, E;
437 DeclContext::lookup_iterator DI, DE;
438 for (I = P.begin(), E = P.end(); I != E; ++I)
439 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
443 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
444 Paths = new CXXBasePaths;
446 addDeclsFromBasePaths(*Paths);
448 setAmbiguous(AmbiguousBaseSubobjects);
451 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
452 Paths = new CXXBasePaths;
454 addDeclsFromBasePaths(*Paths);
456 setAmbiguous(AmbiguousBaseSubobjectTypes);
459 void LookupResult::print(llvm::raw_ostream &Out) {
460 Out << Decls.size() << " result(s)";
461 if (isAmbiguous()) Out << ", ambiguous";
462 if (Paths) Out << ", base paths present";
464 for (iterator I = begin(), E = end(); I != E; ++I) {
470 /// \brief Lookup a builtin function, when name lookup would otherwise
472 static bool LookupBuiltin(Sema &S, LookupResult &R) {
473 Sema::LookupNameKind NameKind = R.getLookupKind();
475 // If we didn't find a use of this identifier, and if the identifier
476 // corresponds to a compiler builtin, create the decl object for the builtin
477 // now, injecting it into translation unit scope, and return it.
478 if (NameKind == Sema::LookupOrdinaryName ||
479 NameKind == Sema::LookupRedeclarationWithLinkage) {
480 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
482 // If this is a builtin on this (or all) targets, create the decl.
483 if (unsigned BuiltinID = II->getBuiltinID()) {
484 // In C++, we don't have any predefined library functions like
485 // 'malloc'. Instead, we'll just error.
486 if (S.getLangOptions().CPlusPlus &&
487 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
490 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
491 BuiltinID, S.TUScope,
492 R.isForRedeclaration(),
498 if (R.isForRedeclaration()) {
499 // If we're redeclaring this function anyway, forget that
500 // this was a builtin at all.
501 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
512 /// \brief Determine whether we can declare a special member function within
513 /// the class at this point.
514 static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
515 const CXXRecordDecl *Class) {
516 // Don't do it if the class is invalid.
517 if (Class->isInvalidDecl())
520 // We need to have a definition for the class.
521 if (!Class->getDefinition() || Class->isDependentContext())
524 // We can't be in the middle of defining the class.
525 if (const RecordType *RecordTy
526 = Context.getTypeDeclType(Class)->getAs<RecordType>())
527 return !RecordTy->isBeingDefined();
532 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
533 if (!CanDeclareSpecialMemberFunction(Context, Class))
536 // If the default constructor has not yet been declared, do so now.
537 if (!Class->hasDeclaredDefaultConstructor())
538 DeclareImplicitDefaultConstructor(Class);
540 // If the copy constructor has not yet been declared, do so now.
541 if (!Class->hasDeclaredCopyConstructor())
542 DeclareImplicitCopyConstructor(Class);
544 // If the copy assignment operator has not yet been declared, do so now.
545 if (!Class->hasDeclaredCopyAssignment())
546 DeclareImplicitCopyAssignment(Class);
548 // If the destructor has not yet been declared, do so now.
549 if (!Class->hasDeclaredDestructor())
550 DeclareImplicitDestructor(Class);
553 /// \brief Determine whether this is the name of an implicitly-declared
554 /// special member function.
555 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
556 switch (Name.getNameKind()) {
557 case DeclarationName::CXXConstructorName:
558 case DeclarationName::CXXDestructorName:
561 case DeclarationName::CXXOperatorName:
562 return Name.getCXXOverloadedOperator() == OO_Equal;
571 /// \brief If there are any implicit member functions with the given name
572 /// that need to be declared in the given declaration context, do so.
573 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
574 DeclarationName Name,
575 const DeclContext *DC) {
579 switch (Name.getNameKind()) {
580 case DeclarationName::CXXConstructorName:
581 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
582 if (Record->getDefinition() &&
583 CanDeclareSpecialMemberFunction(S.Context, Record)) {
584 if (!Record->hasDeclaredDefaultConstructor())
585 S.DeclareImplicitDefaultConstructor(
586 const_cast<CXXRecordDecl *>(Record));
587 if (!Record->hasDeclaredCopyConstructor())
588 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
592 case DeclarationName::CXXDestructorName:
593 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
594 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
595 CanDeclareSpecialMemberFunction(S.Context, Record))
596 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
599 case DeclarationName::CXXOperatorName:
600 if (Name.getCXXOverloadedOperator() != OO_Equal)
603 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
604 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
605 CanDeclareSpecialMemberFunction(S.Context, Record))
606 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
614 // Adds all qualifying matches for a name within a decl context to the
615 // given lookup result. Returns true if any matches were found.
616 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
619 // Lazily declare C++ special member functions.
620 if (S.getLangOptions().CPlusPlus)
621 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
623 // Perform lookup into this declaration context.
624 DeclContext::lookup_const_iterator I, E;
625 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
627 if (R.isAcceptableDecl(D)) {
633 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
636 if (R.getLookupName().getNameKind()
637 != DeclarationName::CXXConversionFunctionName ||
638 R.getLookupName().getCXXNameType()->isDependentType() ||
639 !isa<CXXRecordDecl>(DC))
643 // A specialization of a conversion function template is not found by
644 // name lookup. Instead, any conversion function templates visible in the
645 // context of the use are considered. [...]
646 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
647 if (!Record->isDefinition())
650 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
651 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
652 UEnd = Unresolved->end(); U != UEnd; ++U) {
653 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
657 // When we're performing lookup for the purposes of redeclaration, just
658 // add the conversion function template. When we deduce template
659 // arguments for specializations, we'll end up unifying the return
660 // type of the new declaration with the type of the function template.
661 if (R.isForRedeclaration()) {
662 R.addDecl(ConvTemplate);
668 // [...] For each such operator, if argument deduction succeeds
669 // (14.9.2.3), the resulting specialization is used as if found by
672 // When referencing a conversion function for any purpose other than
673 // a redeclaration (such that we'll be building an expression with the
674 // result), perform template argument deduction and place the
675 // specialization into the result set. We do this to avoid forcing all
676 // callers to perform special deduction for conversion functions.
677 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
678 FunctionDecl *Specialization = 0;
680 const FunctionProtoType *ConvProto
681 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
682 assert(ConvProto && "Nonsensical conversion function template type");
684 // Compute the type of the function that we would expect the conversion
685 // function to have, if it were to match the name given.
686 // FIXME: Calling convention!
687 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
688 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
689 EPI.HasExceptionSpec = false;
690 EPI.HasAnyExceptionSpec = false;
691 EPI.NumExceptions = 0;
692 QualType ExpectedType
693 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
696 // Perform template argument deduction against the type that we would
697 // expect the function to have.
698 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
699 Specialization, Info)
700 == Sema::TDK_Success) {
701 R.addDecl(Specialization);
709 // Performs C++ unqualified lookup into the given file context.
711 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
712 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
714 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
716 // Perform direct name lookup into the LookupCtx.
717 bool Found = LookupDirect(S, R, NS);
719 // Perform direct name lookup into the namespaces nominated by the
720 // using directives whose common ancestor is this namespace.
721 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
722 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
724 for (; UI != UEnd; ++UI)
725 if (LookupDirect(S, R, UI->getNominatedNamespace()))
733 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
734 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
735 return Ctx->isFileContext();
739 // Find the next outer declaration context from this scope. This
740 // routine actually returns the semantic outer context, which may
741 // differ from the lexical context (encoded directly in the Scope
742 // stack) when we are parsing a member of a class template. In this
743 // case, the second element of the pair will be true, to indicate that
744 // name lookup should continue searching in this semantic context when
745 // it leaves the current template parameter scope.
746 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
747 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
748 DeclContext *Lexical = 0;
749 for (Scope *OuterS = S->getParent(); OuterS;
750 OuterS = OuterS->getParent()) {
751 if (OuterS->getEntity()) {
752 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
757 // C++ [temp.local]p8:
758 // In the definition of a member of a class template that appears
759 // outside of the namespace containing the class template
760 // definition, the name of a template-parameter hides the name of
761 // a member of this namespace.
768 // template<class T> class B {
773 // template<class C> void N::B<C>::f(C) {
774 // C b; // C is the template parameter, not N::C
777 // In this example, the lexical context we return is the
778 // TranslationUnit, while the semantic context is the namespace N.
779 if (!Lexical || !DC || !S->getParent() ||
780 !S->getParent()->isTemplateParamScope())
781 return std::make_pair(Lexical, false);
783 // Find the outermost template parameter scope.
784 // For the example, this is the scope for the template parameters of
785 // template<class C>.
786 Scope *OutermostTemplateScope = S->getParent();
787 while (OutermostTemplateScope->getParent() &&
788 OutermostTemplateScope->getParent()->isTemplateParamScope())
789 OutermostTemplateScope = OutermostTemplateScope->getParent();
791 // Find the namespace context in which the original scope occurs. In
792 // the example, this is namespace N.
793 DeclContext *Semantic = DC;
794 while (!Semantic->isFileContext())
795 Semantic = Semantic->getParent();
797 // Find the declaration context just outside of the template
798 // parameter scope. This is the context in which the template is
799 // being lexically declaration (a namespace context). In the
800 // example, this is the global scope.
801 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
802 Lexical->Encloses(Semantic))
803 return std::make_pair(Semantic, true);
805 return std::make_pair(Lexical, false);
808 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
809 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
811 DeclarationName Name = R.getLookupName();
813 // If this is the name of an implicitly-declared special member function,
814 // go through the scope stack to implicitly declare
815 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
816 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
817 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
818 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
821 // Implicitly declare member functions with the name we're looking for, if in
822 // fact we are in a scope where it matters.
825 IdentifierResolver::iterator
826 I = IdResolver.begin(Name),
827 IEnd = IdResolver.end();
829 // First we lookup local scope.
830 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
831 // ...During unqualified name lookup (3.4.1), the names appear as if
832 // they were declared in the nearest enclosing namespace which contains
833 // both the using-directive and the nominated namespace.
834 // [Note: in this context, "contains" means "contains directly or
838 // namespace A { int i; }
842 // using namespace A;
843 // ++i; // finds local 'i', A::i appears at global scope
847 DeclContext *OutsideOfTemplateParamDC = 0;
848 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
849 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
851 // Check whether the IdResolver has anything in this scope.
853 for (; I != IEnd && S->isDeclScope(*I); ++I) {
854 if (R.isAcceptableDecl(*I)) {
861 if (S->isClassScope())
862 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
863 R.setNamingClass(Record);
867 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
868 S->getParent() && !S->getParent()->isTemplateParamScope()) {
869 // We've just searched the last template parameter scope and
870 // found nothing, so look into the the contexts between the
871 // lexical and semantic declaration contexts returned by
872 // findOuterContext(). This implements the name lookup behavior
873 // of C++ [temp.local]p8.
874 Ctx = OutsideOfTemplateParamDC;
875 OutsideOfTemplateParamDC = 0;
879 DeclContext *OuterCtx;
880 bool SearchAfterTemplateScope;
881 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
882 if (SearchAfterTemplateScope)
883 OutsideOfTemplateParamDC = OuterCtx;
885 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
886 // We do not directly look into transparent contexts, since
887 // those entities will be found in the nearest enclosing
888 // non-transparent context.
889 if (Ctx->isTransparentContext())
892 // We do not look directly into function or method contexts,
893 // since all of the local variables and parameters of the
894 // function/method are present within the Scope.
895 if (Ctx->isFunctionOrMethod()) {
896 // If we have an Objective-C instance method, look for ivars
897 // in the corresponding interface.
898 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
899 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
900 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
901 ObjCInterfaceDecl *ClassDeclared;
902 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
903 Name.getAsIdentifierInfo(),
905 if (R.isAcceptableDecl(Ivar)) {
917 // Perform qualified name lookup into this context.
918 // FIXME: In some cases, we know that every name that could be found by
919 // this qualified name lookup will also be on the identifier chain. For
920 // example, inside a class without any base classes, we never need to
921 // perform qualified lookup because all of the members are on top of the
923 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
929 // Stop if we ran out of scopes.
930 // FIXME: This really, really shouldn't be happening.
931 if (!S) return false;
933 // If we are looking for members, no need to look into global/namespace scope.
934 if (R.getLookupKind() == LookupMemberName)
937 // Collect UsingDirectiveDecls in all scopes, and recursively all
938 // nominated namespaces by those using-directives.
940 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
941 // don't build it for each lookup!
943 UnqualUsingDirectiveSet UDirs;
944 UDirs.visitScopeChain(Initial, S);
947 // Lookup namespace scope, and global scope.
948 // Unqualified name lookup in C++ requires looking into scopes
949 // that aren't strictly lexical, and therefore we walk through the
950 // context as well as walking through the scopes.
952 for (; S; S = S->getParent()) {
953 // Check whether the IdResolver has anything in this scope.
955 for (; I != IEnd && S->isDeclScope(*I); ++I) {
956 if (R.isAcceptableDecl(*I)) {
957 // We found something. Look for anything else in our scope
958 // with this same name and in an acceptable identifier
959 // namespace, so that we can construct an overload set if we
966 if (Found && S->isTemplateParamScope()) {
971 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
972 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
973 S->getParent() && !S->getParent()->isTemplateParamScope()) {
974 // We've just searched the last template parameter scope and
975 // found nothing, so look into the the contexts between the
976 // lexical and semantic declaration contexts returned by
977 // findOuterContext(). This implements the name lookup behavior
978 // of C++ [temp.local]p8.
979 Ctx = OutsideOfTemplateParamDC;
980 OutsideOfTemplateParamDC = 0;
984 DeclContext *OuterCtx;
985 bool SearchAfterTemplateScope;
986 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
987 if (SearchAfterTemplateScope)
988 OutsideOfTemplateParamDC = OuterCtx;
990 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
991 // We do not directly look into transparent contexts, since
992 // those entities will be found in the nearest enclosing
993 // non-transparent context.
994 if (Ctx->isTransparentContext())
997 // If we have a context, and it's not a context stashed in the
998 // template parameter scope for an out-of-line definition, also
999 // look into that context.
1000 if (!(Found && S && S->isTemplateParamScope())) {
1001 assert(Ctx->isFileContext() &&
1002 "We should have been looking only at file context here already.");
1004 // Look into context considering using-directives.
1005 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1014 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1019 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1026 /// @brief Perform unqualified name lookup starting from a given
1029 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1030 /// used to find names within the current scope. For example, 'x' in
1034 /// return x; // unqualified name look finds 'x' in the global scope
1038 /// Different lookup criteria can find different names. For example, a
1039 /// particular scope can have both a struct and a function of the same
1040 /// name, and each can be found by certain lookup criteria. For more
1041 /// information about lookup criteria, see the documentation for the
1042 /// class LookupCriteria.
1044 /// @param S The scope from which unqualified name lookup will
1045 /// begin. If the lookup criteria permits, name lookup may also search
1046 /// in the parent scopes.
1048 /// @param Name The name of the entity that we are searching for.
1050 /// @param Loc If provided, the source location where we're performing
1051 /// name lookup. At present, this is only used to produce diagnostics when
1052 /// C library functions (like "malloc") are implicitly declared.
1054 /// @returns The result of name lookup, which includes zero or more
1055 /// declarations and possibly additional information used to diagnose
1057 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1058 DeclarationName Name = R.getLookupName();
1059 if (!Name) return false;
1061 LookupNameKind NameKind = R.getLookupKind();
1063 if (!getLangOptions().CPlusPlus) {
1064 // Unqualified name lookup in C/Objective-C is purely lexical, so
1065 // search in the declarations attached to the name.
1066 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1067 // Find the nearest non-transparent declaration scope.
1068 while (!(S->getFlags() & Scope::DeclScope) ||
1070 static_cast<DeclContext *>(S->getEntity())
1071 ->isTransparentContext()))
1075 unsigned IDNS = R.getIdentifierNamespace();
1077 // Scan up the scope chain looking for a decl that matches this
1078 // identifier that is in the appropriate namespace. This search
1079 // should not take long, as shadowing of names is uncommon, and
1080 // deep shadowing is extremely uncommon.
1081 bool LeftStartingScope = false;
1083 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1084 IEnd = IdResolver.end();
1086 if ((*I)->isInIdentifierNamespace(IDNS)) {
1087 if (NameKind == LookupRedeclarationWithLinkage) {
1088 // Determine whether this (or a previous) declaration is
1090 if (!LeftStartingScope && !S->isDeclScope(*I))
1091 LeftStartingScope = true;
1093 // If we found something outside of our starting scope that
1094 // does not have linkage, skip it.
1095 if (LeftStartingScope && !((*I)->hasLinkage()))
1101 if ((*I)->getAttr<OverloadableAttr>()) {
1102 // If this declaration has the "overloadable" attribute, we
1103 // might have a set of overloaded functions.
1105 // Figure out what scope the identifier is in.
1106 while (!(S->getFlags() & Scope::DeclScope) ||
1107 !S->isDeclScope(*I))
1110 // Find the last declaration in this scope (with the same
1111 // name, naturally).
1112 IdentifierResolver::iterator LastI = I;
1113 for (++LastI; LastI != IEnd; ++LastI) {
1114 if (!S->isDeclScope(*LastI))
1125 // Perform C++ unqualified name lookup.
1126 if (CppLookupName(R, S))
1130 // If we didn't find a use of this identifier, and if the identifier
1131 // corresponds to a compiler builtin, create the decl object for the builtin
1132 // now, injecting it into translation unit scope, and return it.
1133 if (AllowBuiltinCreation)
1134 return LookupBuiltin(*this, R);
1136 // If we didn't find a use of this identifier, the ExternalSource
1137 // may be able to handle the situation.
1138 // Note: some lookup failures are expected!
1139 // See e.g. R.isForRedeclaration().
1140 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1143 /// @brief Perform qualified name lookup in the namespaces nominated by
1144 /// using directives by the given context.
1146 /// C++98 [namespace.qual]p2:
1147 /// Given X::m (where X is a user-declared namespace), or given ::m
1148 /// (where X is the global namespace), let S be the set of all
1149 /// declarations of m in X and in the transitive closure of all
1150 /// namespaces nominated by using-directives in X and its used
1151 /// namespaces, except that using-directives are ignored in any
1152 /// namespace, including X, directly containing one or more
1153 /// declarations of m. No namespace is searched more than once in
1154 /// the lookup of a name. If S is the empty set, the program is
1155 /// ill-formed. Otherwise, if S has exactly one member, or if the
1156 /// context of the reference is a using-declaration
1157 /// (namespace.udecl), S is the required set of declarations of
1158 /// m. Otherwise if the use of m is not one that allows a unique
1159 /// declaration to be chosen from S, the program is ill-formed.
1160 /// C++98 [namespace.qual]p5:
1161 /// During the lookup of a qualified namespace member name, if the
1162 /// lookup finds more than one declaration of the member, and if one
1163 /// declaration introduces a class name or enumeration name and the
1164 /// other declarations either introduce the same object, the same
1165 /// enumerator or a set of functions, the non-type name hides the
1166 /// class or enumeration name if and only if the declarations are
1167 /// from the same namespace; otherwise (the declarations are from
1168 /// different namespaces), the program is ill-formed.
1169 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1170 DeclContext *StartDC) {
1171 assert(StartDC->isFileContext() && "start context is not a file context");
1173 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1174 DeclContext::udir_iterator E = StartDC->using_directives_end();
1176 if (I == E) return false;
1178 // We have at least added all these contexts to the queue.
1179 llvm::DenseSet<DeclContext*> Visited;
1180 Visited.insert(StartDC);
1182 // We have not yet looked into these namespaces, much less added
1183 // their "using-children" to the queue.
1184 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1186 // We have already looked into the initial namespace; seed the queue
1187 // with its using-children.
1188 for (; I != E; ++I) {
1189 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1190 if (Visited.insert(ND).second)
1191 Queue.push_back(ND);
1194 // The easiest way to implement the restriction in [namespace.qual]p5
1195 // is to check whether any of the individual results found a tag
1196 // and, if so, to declare an ambiguity if the final result is not
1198 bool FoundTag = false;
1199 bool FoundNonTag = false;
1201 LookupResult LocalR(LookupResult::Temporary, R);
1204 while (!Queue.empty()) {
1205 NamespaceDecl *ND = Queue.back();
1208 // We go through some convolutions here to avoid copying results
1209 // between LookupResults.
1210 bool UseLocal = !R.empty();
1211 LookupResult &DirectR = UseLocal ? LocalR : R;
1212 bool FoundDirect = LookupDirect(S, DirectR, ND);
1215 // First do any local hiding.
1216 DirectR.resolveKind();
1218 // If the local result is a tag, remember that.
1219 if (DirectR.isSingleTagDecl())
1224 // Append the local results to the total results if necessary.
1226 R.addAllDecls(LocalR);
1231 // If we find names in this namespace, ignore its using directives.
1237 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1238 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1239 if (Visited.insert(Nom).second)
1240 Queue.push_back(Nom);
1245 if (FoundTag && FoundNonTag)
1246 R.setAmbiguousQualifiedTagHiding();
1254 /// \brief Callback that looks for any member of a class with the given name.
1255 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1258 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1260 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1261 Path.Decls = BaseRecord->lookup(N);
1262 return Path.Decls.first != Path.Decls.second;
1265 /// \brief Determine whether the given set of member declarations contains only
1266 /// static members, nested types, and enumerators.
1267 template<typename InputIterator>
1268 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1269 Decl *D = (*First)->getUnderlyingDecl();
1270 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1273 if (isa<CXXMethodDecl>(D)) {
1274 // Determine whether all of the methods are static.
1275 bool AllMethodsAreStatic = true;
1276 for(; First != Last; ++First) {
1277 D = (*First)->getUnderlyingDecl();
1279 if (!isa<CXXMethodDecl>(D)) {
1280 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1284 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1285 AllMethodsAreStatic = false;
1290 if (AllMethodsAreStatic)
1297 /// \brief Perform qualified name lookup into a given context.
1299 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1300 /// names when the context of those names is explicit specified, e.g.,
1301 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1303 /// Different lookup criteria can find different names. For example, a
1304 /// particular scope can have both a struct and a function of the same
1305 /// name, and each can be found by certain lookup criteria. For more
1306 /// information about lookup criteria, see the documentation for the
1307 /// class LookupCriteria.
1309 /// \param R captures both the lookup criteria and any lookup results found.
1311 /// \param LookupCtx The context in which qualified name lookup will
1312 /// search. If the lookup criteria permits, name lookup may also search
1313 /// in the parent contexts or (for C++ classes) base classes.
1315 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1316 /// occurs as part of unqualified name lookup.
1318 /// \returns true if lookup succeeded, false if it failed.
1319 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1320 bool InUnqualifiedLookup) {
1321 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1323 if (!R.getLookupName())
1326 // Make sure that the declaration context is complete.
1327 assert((!isa<TagDecl>(LookupCtx) ||
1328 LookupCtx->isDependentContext() ||
1329 cast<TagDecl>(LookupCtx)->isDefinition() ||
1330 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1331 ->isBeingDefined()) &&
1332 "Declaration context must already be complete!");
1334 // Perform qualified name lookup into the LookupCtx.
1335 if (LookupDirect(*this, R, LookupCtx)) {
1337 if (isa<CXXRecordDecl>(LookupCtx))
1338 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1342 // Don't descend into implied contexts for redeclarations.
1343 // C++98 [namespace.qual]p6:
1344 // In a declaration for a namespace member in which the
1345 // declarator-id is a qualified-id, given that the qualified-id
1346 // for the namespace member has the form
1347 // nested-name-specifier unqualified-id
1348 // the unqualified-id shall name a member of the namespace
1349 // designated by the nested-name-specifier.
1350 // See also [class.mfct]p5 and [class.static.data]p2.
1351 if (R.isForRedeclaration())
1354 // If this is a namespace, look it up in the implied namespaces.
1355 if (LookupCtx->isFileContext())
1356 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1358 // If this isn't a C++ class, we aren't allowed to look into base
1359 // classes, we're done.
1360 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1361 if (!LookupRec || !LookupRec->getDefinition())
1364 // If we're performing qualified name lookup into a dependent class,
1365 // then we are actually looking into a current instantiation. If we have any
1366 // dependent base classes, then we either have to delay lookup until
1367 // template instantiation time (at which point all bases will be available)
1368 // or we have to fail.
1369 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1370 LookupRec->hasAnyDependentBases()) {
1371 R.setNotFoundInCurrentInstantiation();
1375 // Perform lookup into our base classes.
1377 Paths.setOrigin(LookupRec);
1379 // Look for this member in our base classes
1380 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1381 switch (R.getLookupKind()) {
1382 case LookupOrdinaryName:
1383 case LookupMemberName:
1384 case LookupRedeclarationWithLinkage:
1385 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1389 BaseCallback = &CXXRecordDecl::FindTagMember;
1393 BaseCallback = &LookupAnyMember;
1396 case LookupUsingDeclName:
1397 // This lookup is for redeclarations only.
1399 case LookupOperatorName:
1400 case LookupNamespaceName:
1401 case LookupObjCProtocolName:
1403 // These lookups will never find a member in a C++ class (or base class).
1406 case LookupNestedNameSpecifierName:
1407 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1411 if (!LookupRec->lookupInBases(BaseCallback,
1412 R.getLookupName().getAsOpaquePtr(), Paths))
1415 R.setNamingClass(LookupRec);
1417 // C++ [class.member.lookup]p2:
1418 // [...] If the resulting set of declarations are not all from
1419 // sub-objects of the same type, or the set has a nonstatic member
1420 // and includes members from distinct sub-objects, there is an
1421 // ambiguity and the program is ill-formed. Otherwise that set is
1422 // the result of the lookup.
1423 QualType SubobjectType;
1424 int SubobjectNumber = 0;
1425 AccessSpecifier SubobjectAccess = AS_none;
1427 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1428 Path != PathEnd; ++Path) {
1429 const CXXBasePathElement &PathElement = Path->back();
1431 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1432 // across all paths.
1433 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1435 // Determine whether we're looking at a distinct sub-object or not.
1436 if (SubobjectType.isNull()) {
1437 // This is the first subobject we've looked at. Record its type.
1438 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1439 SubobjectNumber = PathElement.SubobjectNumber;
1444 != Context.getCanonicalType(PathElement.Base->getType())) {
1445 // We found members of the given name in two subobjects of
1446 // different types. If the declaration sets aren't the same, this
1447 // this lookup is ambiguous.
1448 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1449 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1450 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1451 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1453 while (FirstD != FirstPath->Decls.second &&
1454 CurrentD != Path->Decls.second) {
1455 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1456 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1463 if (FirstD == FirstPath->Decls.second &&
1464 CurrentD == Path->Decls.second)
1468 R.setAmbiguousBaseSubobjectTypes(Paths);
1472 if (SubobjectNumber != PathElement.SubobjectNumber) {
1473 // We have a different subobject of the same type.
1475 // C++ [class.member.lookup]p5:
1476 // A static member, a nested type or an enumerator defined in
1477 // a base class T can unambiguously be found even if an object
1478 // has more than one base class subobject of type T.
1479 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
1482 // We have found a nonstatic member name in multiple, distinct
1483 // subobjects. Name lookup is ambiguous.
1484 R.setAmbiguousBaseSubobjects(Paths);
1489 // Lookup in a base class succeeded; return these results.
1491 DeclContext::lookup_iterator I, E;
1492 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1494 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1502 /// @brief Performs name lookup for a name that was parsed in the
1503 /// source code, and may contain a C++ scope specifier.
1505 /// This routine is a convenience routine meant to be called from
1506 /// contexts that receive a name and an optional C++ scope specifier
1507 /// (e.g., "N::M::x"). It will then perform either qualified or
1508 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1509 /// respectively) on the given name and return those results.
1511 /// @param S The scope from which unqualified name lookup will
1514 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1516 /// @param EnteringContext Indicates whether we are going to enter the
1517 /// context of the scope-specifier SS (if present).
1519 /// @returns True if any decls were found (but possibly ambiguous)
1520 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1521 bool AllowBuiltinCreation, bool EnteringContext) {
1522 if (SS && SS->isInvalid()) {
1523 // When the scope specifier is invalid, don't even look for
1528 if (SS && SS->isSet()) {
1529 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1530 // We have resolved the scope specifier to a particular declaration
1531 // contex, and will perform name lookup in that context.
1532 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1535 R.setContextRange(SS->getRange());
1537 return LookupQualifiedName(R, DC);
1540 // We could not resolve the scope specified to a specific declaration
1541 // context, which means that SS refers to an unknown specialization.
1542 // Name lookup can't find anything in this case.
1546 // Perform unqualified name lookup starting in the given scope.
1547 return LookupName(R, S, AllowBuiltinCreation);
1551 /// @brief Produce a diagnostic describing the ambiguity that resulted
1552 /// from name lookup.
1554 /// @param Result The ambiguous name lookup result.
1556 /// @param Name The name of the entity that name lookup was
1559 /// @param NameLoc The location of the name within the source code.
1561 /// @param LookupRange A source range that provides more
1562 /// source-location information concerning the lookup itself. For
1563 /// example, this range might highlight a nested-name-specifier that
1564 /// precedes the name.
1567 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1568 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1570 DeclarationName Name = Result.getLookupName();
1571 SourceLocation NameLoc = Result.getNameLoc();
1572 SourceRange LookupRange = Result.getContextRange();
1574 switch (Result.getAmbiguityKind()) {
1575 case LookupResult::AmbiguousBaseSubobjects: {
1576 CXXBasePaths *Paths = Result.getBasePaths();
1577 QualType SubobjectType = Paths->front().back().Base->getType();
1578 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1579 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1582 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1583 while (isa<CXXMethodDecl>(*Found) &&
1584 cast<CXXMethodDecl>(*Found)->isStatic())
1587 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1592 case LookupResult::AmbiguousBaseSubobjectTypes: {
1593 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1594 << Name << LookupRange;
1596 CXXBasePaths *Paths = Result.getBasePaths();
1597 std::set<Decl *> DeclsPrinted;
1598 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1599 PathEnd = Paths->end();
1600 Path != PathEnd; ++Path) {
1601 Decl *D = *Path->Decls.first;
1602 if (DeclsPrinted.insert(D).second)
1603 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1609 case LookupResult::AmbiguousTagHiding: {
1610 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1612 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1614 LookupResult::iterator DI, DE = Result.end();
1615 for (DI = Result.begin(); DI != DE; ++DI)
1616 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1617 TagDecls.insert(TD);
1618 Diag(TD->getLocation(), diag::note_hidden_tag);
1621 for (DI = Result.begin(); DI != DE; ++DI)
1622 if (!isa<TagDecl>(*DI))
1623 Diag((*DI)->getLocation(), diag::note_hiding_object);
1625 // For recovery purposes, go ahead and implement the hiding.
1626 LookupResult::Filter F = Result.makeFilter();
1627 while (F.hasNext()) {
1628 if (TagDecls.count(F.next()))
1636 case LookupResult::AmbiguousReference: {
1637 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1639 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1640 for (; DI != DE; ++DI)
1641 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1647 llvm_unreachable("unknown ambiguity kind");
1652 struct AssociatedLookup {
1653 AssociatedLookup(Sema &S,
1654 Sema::AssociatedNamespaceSet &Namespaces,
1655 Sema::AssociatedClassSet &Classes)
1656 : S(S), Namespaces(Namespaces), Classes(Classes) {
1660 Sema::AssociatedNamespaceSet &Namespaces;
1661 Sema::AssociatedClassSet &Classes;
1666 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1668 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1670 // Add the associated namespace for this class.
1672 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1673 // be a locally scoped record.
1675 // We skip out of inline namespaces. The innermost non-inline namespace
1676 // contains all names of all its nested inline namespaces anyway, so we can
1677 // replace the entire inline namespace tree with its root.
1678 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1679 Ctx->isInlineNamespace())
1680 Ctx = Ctx->getParent();
1682 if (Ctx->isFileContext())
1683 Namespaces.insert(Ctx->getPrimaryContext());
1686 // \brief Add the associated classes and namespaces for argument-dependent
1687 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1689 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1690 const TemplateArgument &Arg) {
1691 // C++ [basic.lookup.koenig]p2, last bullet:
1693 switch (Arg.getKind()) {
1694 case TemplateArgument::Null:
1697 case TemplateArgument::Type:
1698 // [...] the namespaces and classes associated with the types of the
1699 // template arguments provided for template type parameters (excluding
1700 // template template parameters)
1701 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1704 case TemplateArgument::Template:
1705 case TemplateArgument::TemplateExpansion: {
1706 // [...] the namespaces in which any template template arguments are
1707 // defined; and the classes in which any member templates used as
1708 // template template arguments are defined.
1709 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1710 if (ClassTemplateDecl *ClassTemplate
1711 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1712 DeclContext *Ctx = ClassTemplate->getDeclContext();
1713 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1714 Result.Classes.insert(EnclosingClass);
1715 // Add the associated namespace for this class.
1716 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1721 case TemplateArgument::Declaration:
1722 case TemplateArgument::Integral:
1723 case TemplateArgument::Expression:
1724 // [Note: non-type template arguments do not contribute to the set of
1725 // associated namespaces. ]
1728 case TemplateArgument::Pack:
1729 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1730 PEnd = Arg.pack_end();
1732 addAssociatedClassesAndNamespaces(Result, *P);
1737 // \brief Add the associated classes and namespaces for
1738 // argument-dependent lookup with an argument of class type
1739 // (C++ [basic.lookup.koenig]p2).
1741 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1742 CXXRecordDecl *Class) {
1744 // Just silently ignore anything whose name is __va_list_tag.
1745 if (Class->getDeclName() == Result.S.VAListTagName)
1748 // C++ [basic.lookup.koenig]p2:
1750 // -- If T is a class type (including unions), its associated
1751 // classes are: the class itself; the class of which it is a
1752 // member, if any; and its direct and indirect base
1753 // classes. Its associated namespaces are the namespaces in
1754 // which its associated classes are defined.
1756 // Add the class of which it is a member, if any.
1757 DeclContext *Ctx = Class->getDeclContext();
1758 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1759 Result.Classes.insert(EnclosingClass);
1760 // Add the associated namespace for this class.
1761 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1763 // Add the class itself. If we've already seen this class, we don't
1764 // need to visit base classes.
1765 if (!Result.Classes.insert(Class))
1768 // -- If T is a template-id, its associated namespaces and classes are
1769 // the namespace in which the template is defined; for member
1770 // templates, the member template's class; the namespaces and classes
1771 // associated with the types of the template arguments provided for
1772 // template type parameters (excluding template template parameters); the
1773 // namespaces in which any template template arguments are defined; and
1774 // the classes in which any member templates used as template template
1775 // arguments are defined. [Note: non-type template arguments do not
1776 // contribute to the set of associated namespaces. ]
1777 if (ClassTemplateSpecializationDecl *Spec
1778 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1779 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1780 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1781 Result.Classes.insert(EnclosingClass);
1782 // Add the associated namespace for this class.
1783 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1785 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1786 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1787 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
1790 // Only recurse into base classes for complete types.
1791 if (!Class->hasDefinition()) {
1792 // FIXME: we might need to instantiate templates here
1796 // Add direct and indirect base classes along with their associated
1798 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1799 Bases.push_back(Class);
1800 while (!Bases.empty()) {
1801 // Pop this class off the stack.
1802 Class = Bases.back();
1805 // Visit the base classes.
1806 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1807 BaseEnd = Class->bases_end();
1808 Base != BaseEnd; ++Base) {
1809 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1810 // In dependent contexts, we do ADL twice, and the first time around,
1811 // the base type might be a dependent TemplateSpecializationType, or a
1812 // TemplateTypeParmType. If that happens, simply ignore it.
1813 // FIXME: If we want to support export, we probably need to add the
1814 // namespace of the template in a TemplateSpecializationType, or even
1815 // the classes and namespaces of known non-dependent arguments.
1818 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1819 if (Result.Classes.insert(BaseDecl)) {
1820 // Find the associated namespace for this base class.
1821 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1822 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
1824 // Make sure we visit the bases of this base class.
1825 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1826 Bases.push_back(BaseDecl);
1832 // \brief Add the associated classes and namespaces for
1833 // argument-dependent lookup with an argument of type T
1834 // (C++ [basic.lookup.koenig]p2).
1836 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
1837 // C++ [basic.lookup.koenig]p2:
1839 // For each argument type T in the function call, there is a set
1840 // of zero or more associated namespaces and a set of zero or more
1841 // associated classes to be considered. The sets of namespaces and
1842 // classes is determined entirely by the types of the function
1843 // arguments (and the namespace of any template template
1844 // argument). Typedef names and using-declarations used to specify
1845 // the types do not contribute to this set. The sets of namespaces
1846 // and classes are determined in the following way:
1848 llvm::SmallVector<const Type *, 16> Queue;
1849 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1852 switch (T->getTypeClass()) {
1854 #define TYPE(Class, Base)
1855 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1856 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1857 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1858 #define ABSTRACT_TYPE(Class, Base)
1859 #include "clang/AST/TypeNodes.def"
1860 // T is canonical. We can also ignore dependent types because
1861 // we don't need to do ADL at the definition point, but if we
1862 // wanted to implement template export (or if we find some other
1863 // use for associated classes and namespaces...) this would be
1867 // -- If T is a pointer to U or an array of U, its associated
1868 // namespaces and classes are those associated with U.
1870 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1872 case Type::ConstantArray:
1873 case Type::IncompleteArray:
1874 case Type::VariableArray:
1875 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1878 // -- If T is a fundamental type, its associated sets of
1879 // namespaces and classes are both empty.
1883 // -- If T is a class type (including unions), its associated
1884 // classes are: the class itself; the class of which it is a
1885 // member, if any; and its direct and indirect base
1886 // classes. Its associated namespaces are the namespaces in
1887 // which its associated classes are defined.
1888 case Type::Record: {
1889 CXXRecordDecl *Class
1890 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
1891 addAssociatedClassesAndNamespaces(Result, Class);
1895 // -- If T is an enumeration type, its associated namespace is
1896 // the namespace in which it is defined. If it is class
1897 // member, its associated class is the member's class; else
1898 // it has no associated class.
1900 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
1902 DeclContext *Ctx = Enum->getDeclContext();
1903 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1904 Result.Classes.insert(EnclosingClass);
1906 // Add the associated namespace for this class.
1907 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1912 // -- If T is a function type, its associated namespaces and
1913 // classes are those associated with the function parameter
1914 // types and those associated with the return type.
1915 case Type::FunctionProto: {
1916 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1917 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1918 ArgEnd = Proto->arg_type_end();
1919 Arg != ArgEnd; ++Arg)
1920 Queue.push_back(Arg->getTypePtr());
1923 case Type::FunctionNoProto: {
1924 const FunctionType *FnType = cast<FunctionType>(T);
1925 T = FnType->getResultType().getTypePtr();
1929 // -- If T is a pointer to a member function of a class X, its
1930 // associated namespaces and classes are those associated
1931 // with the function parameter types and return type,
1932 // together with those associated with X.
1934 // -- If T is a pointer to a data member of class X, its
1935 // associated namespaces and classes are those associated
1936 // with the member type together with those associated with
1938 case Type::MemberPointer: {
1939 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1941 // Queue up the class type into which this points.
1942 Queue.push_back(MemberPtr->getClass());
1944 // And directly continue with the pointee type.
1945 T = MemberPtr->getPointeeType().getTypePtr();
1949 // As an extension, treat this like a normal pointer.
1950 case Type::BlockPointer:
1951 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1954 // References aren't covered by the standard, but that's such an
1955 // obvious defect that we cover them anyway.
1956 case Type::LValueReference:
1957 case Type::RValueReference:
1958 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1961 // These are fundamental types.
1963 case Type::ExtVector:
1967 // These are ignored by ADL.
1968 case Type::ObjCObject:
1969 case Type::ObjCInterface:
1970 case Type::ObjCObjectPointer:
1974 if (Queue.empty()) break;
1980 /// \brief Find the associated classes and namespaces for
1981 /// argument-dependent lookup for a call with the given set of
1984 /// This routine computes the sets of associated classes and associated
1985 /// namespaces searched by argument-dependent lookup
1986 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1988 Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1989 AssociatedNamespaceSet &AssociatedNamespaces,
1990 AssociatedClassSet &AssociatedClasses) {
1991 AssociatedNamespaces.clear();
1992 AssociatedClasses.clear();
1994 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1996 // C++ [basic.lookup.koenig]p2:
1997 // For each argument type T in the function call, there is a set
1998 // of zero or more associated namespaces and a set of zero or more
1999 // associated classes to be considered. The sets of namespaces and
2000 // classes is determined entirely by the types of the function
2001 // arguments (and the namespace of any template template
2003 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2004 Expr *Arg = Args[ArgIdx];
2006 if (Arg->getType() != Context.OverloadTy) {
2007 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2011 // [...] In addition, if the argument is the name or address of a
2012 // set of overloaded functions and/or function templates, its
2013 // associated classes and namespaces are the union of those
2014 // associated with each of the members of the set: the namespace
2015 // in which the function or function template is defined and the
2016 // classes and namespaces associated with its (non-dependent)
2017 // parameter types and return type.
2018 Arg = Arg->IgnoreParens();
2019 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2020 if (unaryOp->getOpcode() == UO_AddrOf)
2021 Arg = unaryOp->getSubExpr();
2023 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2026 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2028 // Look through any using declarations to find the underlying function.
2029 NamedDecl *Fn = (*I)->getUnderlyingDecl();
2031 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2033 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2035 // Add the classes and namespaces associated with the parameter
2036 // types and return type of this function.
2037 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2042 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2043 /// an acceptable non-member overloaded operator for a call whose
2044 /// arguments have types T1 (and, if non-empty, T2). This routine
2045 /// implements the check in C++ [over.match.oper]p3b2 concerning
2046 /// enumeration types.
2048 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2049 QualType T1, QualType T2,
2050 ASTContext &Context) {
2051 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2054 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2057 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2058 if (Proto->getNumArgs() < 1)
2061 if (T1->isEnumeralType()) {
2062 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2063 if (Context.hasSameUnqualifiedType(T1, ArgType))
2067 if (Proto->getNumArgs() < 2)
2070 if (!T2.isNull() && T2->isEnumeralType()) {
2071 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2072 if (Context.hasSameUnqualifiedType(T2, ArgType))
2079 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2081 LookupNameKind NameKind,
2082 RedeclarationKind Redecl) {
2083 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2085 return R.getAsSingle<NamedDecl>();
2088 /// \brief Find the protocol with the given name, if any.
2089 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2090 SourceLocation IdLoc) {
2091 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2092 LookupObjCProtocolName);
2093 return cast_or_null<ObjCProtocolDecl>(D);
2096 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2097 QualType T1, QualType T2,
2098 UnresolvedSetImpl &Functions) {
2099 // C++ [over.match.oper]p3:
2100 // -- The set of non-member candidates is the result of the
2101 // unqualified lookup of operator@ in the context of the
2102 // expression according to the usual rules for name lookup in
2103 // unqualified function calls (3.4.2) except that all member
2104 // functions are ignored. However, if no operand has a class
2105 // type, only those non-member functions in the lookup set
2106 // that have a first parameter of type T1 or "reference to
2107 // (possibly cv-qualified) T1", when T1 is an enumeration
2108 // type, or (if there is a right operand) a second parameter
2109 // of type T2 or "reference to (possibly cv-qualified) T2",
2110 // when T2 is an enumeration type, are candidate functions.
2111 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2112 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2113 LookupName(Operators, S);
2115 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2117 if (Operators.empty())
2120 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2121 Op != OpEnd; ++Op) {
2122 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2123 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2124 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2125 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2126 } else if (FunctionTemplateDecl *FunTmpl
2127 = dyn_cast<FunctionTemplateDecl>(Found)) {
2128 // FIXME: friend operators?
2129 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2131 if (!FunTmpl->getDeclContext()->isRecord())
2132 Functions.addDecl(*Op, Op.getAccess());
2137 /// \brief Look up the constructors for the given class.
2138 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2139 // If the copy constructor has not yet been declared, do so now.
2140 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2141 if (!Class->hasDeclaredDefaultConstructor())
2142 DeclareImplicitDefaultConstructor(Class);
2143 if (!Class->hasDeclaredCopyConstructor())
2144 DeclareImplicitCopyConstructor(Class);
2147 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2148 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2149 return Class->lookup(Name);
2152 /// \brief Look for the destructor of the given class.
2154 /// During semantic analysis, this routine should be used in lieu of
2155 /// CXXRecordDecl::getDestructor().
2157 /// \returns The destructor for this class.
2158 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2159 // If the destructor has not yet been declared, do so now.
2160 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2161 !Class->hasDeclaredDestructor())
2162 DeclareImplicitDestructor(Class);
2164 return Class->getDestructor();
2167 void ADLResult::insert(NamedDecl *New) {
2168 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2170 // If we haven't yet seen a decl for this key, or the last decl
2171 // was exactly this one, we're done.
2172 if (Old == 0 || Old == New) {
2177 // Otherwise, decide which is a more recent redeclaration.
2178 FunctionDecl *OldFD, *NewFD;
2179 if (isa<FunctionTemplateDecl>(New)) {
2180 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2181 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2183 OldFD = cast<FunctionDecl>(Old);
2184 NewFD = cast<FunctionDecl>(New);
2187 FunctionDecl *Cursor = NewFD;
2189 Cursor = Cursor->getPreviousDeclaration();
2191 // If we got to the end without finding OldFD, OldFD is the newer
2192 // declaration; leave things as they are.
2193 if (!Cursor) return;
2195 // If we do find OldFD, then NewFD is newer.
2196 if (Cursor == OldFD) break;
2198 // Otherwise, keep looking.
2204 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2205 Expr **Args, unsigned NumArgs,
2206 ADLResult &Result) {
2207 // Find all of the associated namespaces and classes based on the
2208 // arguments we have.
2209 AssociatedNamespaceSet AssociatedNamespaces;
2210 AssociatedClassSet AssociatedClasses;
2211 FindAssociatedClassesAndNamespaces(Args, NumArgs,
2212 AssociatedNamespaces,
2217 T1 = Args[0]->getType();
2219 T2 = Args[1]->getType();
2222 // C++ [basic.lookup.argdep]p3:
2223 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2224 // and let Y be the lookup set produced by argument dependent
2225 // lookup (defined as follows). If X contains [...] then Y is
2226 // empty. Otherwise Y is the set of declarations found in the
2227 // namespaces associated with the argument types as described
2228 // below. The set of declarations found by the lookup of the name
2229 // is the union of X and Y.
2231 // Here, we compute Y and add its members to the overloaded
2233 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2234 NSEnd = AssociatedNamespaces.end();
2235 NS != NSEnd; ++NS) {
2236 // When considering an associated namespace, the lookup is the
2237 // same as the lookup performed when the associated namespace is
2238 // used as a qualifier (3.4.3.2) except that:
2240 // -- Any using-directives in the associated namespace are
2243 // -- Any namespace-scope friend functions declared in
2244 // associated classes are visible within their respective
2245 // namespaces even if they are not visible during an ordinary
2247 DeclContext::lookup_iterator I, E;
2248 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
2250 // If the only declaration here is an ordinary friend, consider
2251 // it only if it was declared in an associated classes.
2252 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
2253 DeclContext *LexDC = D->getLexicalDeclContext();
2254 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2258 if (isa<UsingShadowDecl>(D))
2259 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2261 if (isa<FunctionDecl>(D)) {
2263 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2266 } else if (!isa<FunctionTemplateDecl>(D))
2274 //----------------------------------------------------------------------------
2275 // Search for all visible declarations.
2276 //----------------------------------------------------------------------------
2277 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2281 class ShadowContextRAII;
2283 class VisibleDeclsRecord {
2285 /// \brief An entry in the shadow map, which is optimized to store a
2286 /// single declaration (the common case) but can also store a list
2287 /// of declarations.
2288 class ShadowMapEntry {
2289 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2291 /// \brief Contains either the solitary NamedDecl * or a vector
2292 /// of declarations.
2293 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2296 ShadowMapEntry() : DeclOrVector() { }
2298 void Add(NamedDecl *ND);
2302 typedef NamedDecl * const *iterator;
2308 /// \brief A mapping from declaration names to the declarations that have
2309 /// this name within a particular scope.
2310 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2312 /// \brief A list of shadow maps, which is used to model name hiding.
2313 std::list<ShadowMap> ShadowMaps;
2315 /// \brief The declaration contexts we have already visited.
2316 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2318 friend class ShadowContextRAII;
2321 /// \brief Determine whether we have already visited this context
2322 /// (and, if not, note that we are going to visit that context now).
2323 bool visitedContext(DeclContext *Ctx) {
2324 return !VisitedContexts.insert(Ctx);
2327 bool alreadyVisitedContext(DeclContext *Ctx) {
2328 return VisitedContexts.count(Ctx);
2331 /// \brief Determine whether the given declaration is hidden in the
2334 /// \returns the declaration that hides the given declaration, or
2335 /// NULL if no such declaration exists.
2336 NamedDecl *checkHidden(NamedDecl *ND);
2338 /// \brief Add a declaration to the current shadow map.
2339 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2342 /// \brief RAII object that records when we've entered a shadow context.
2343 class ShadowContextRAII {
2344 VisibleDeclsRecord &Visible;
2346 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2349 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2350 Visible.ShadowMaps.push_back(ShadowMap());
2353 ~ShadowContextRAII() {
2354 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2355 EEnd = Visible.ShadowMaps.back().end();
2358 E->second.Destroy();
2360 Visible.ShadowMaps.pop_back();
2364 } // end anonymous namespace
2366 void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2367 if (DeclOrVector.isNull()) {
2368 // 0 - > 1 elements: just set the single element information.
2373 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2374 // 1 -> 2 elements: create the vector of results and push in the
2375 // existing declaration.
2376 DeclVector *Vec = new DeclVector;
2377 Vec->push_back(PrevND);
2381 // Add the new element to the end of the vector.
2382 DeclOrVector.get<DeclVector*>()->push_back(ND);
2385 void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2386 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2388 DeclOrVector = ((NamedDecl *)0);
2392 VisibleDeclsRecord::ShadowMapEntry::iterator
2393 VisibleDeclsRecord::ShadowMapEntry::begin() {
2394 if (DeclOrVector.isNull())
2397 if (DeclOrVector.is<NamedDecl *>())
2398 return DeclOrVector.getAddrOf<NamedDecl *>();
2400 return DeclOrVector.get<DeclVector *>()->begin();
2403 VisibleDeclsRecord::ShadowMapEntry::iterator
2404 VisibleDeclsRecord::ShadowMapEntry::end() {
2405 if (DeclOrVector.isNull())
2408 if (DeclOrVector.dyn_cast<NamedDecl *>())
2409 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2411 return DeclOrVector.get<DeclVector *>()->end();
2414 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2415 // Look through using declarations.
2416 ND = ND->getUnderlyingDecl();
2418 unsigned IDNS = ND->getIdentifierNamespace();
2419 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2420 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2421 SM != SMEnd; ++SM) {
2422 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2423 if (Pos == SM->end())
2426 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2427 IEnd = Pos->second.end();
2429 // A tag declaration does not hide a non-tag declaration.
2430 if ((*I)->hasTagIdentifierNamespace() &&
2431 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2432 Decl::IDNS_ObjCProtocol)))
2435 // Protocols are in distinct namespaces from everything else.
2436 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2437 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2438 (*I)->getIdentifierNamespace() != IDNS)
2441 // Functions and function templates in the same scope overload
2442 // rather than hide. FIXME: Look for hiding based on function
2444 if ((*I)->isFunctionOrFunctionTemplate() &&
2445 ND->isFunctionOrFunctionTemplate() &&
2446 SM == ShadowMaps.rbegin())
2449 // We've found a declaration that hides this one.
2457 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2458 bool QualifiedNameLookup,
2460 VisibleDeclConsumer &Consumer,
2461 VisibleDeclsRecord &Visited) {
2465 // Make sure we don't visit the same context twice.
2466 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2469 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2470 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2472 // Enumerate all of the results in this context.
2473 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2474 CurCtx = CurCtx->getNextContext()) {
2475 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2476 DEnd = CurCtx->decls_end();
2478 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
2479 if (Result.isAcceptableDecl(ND)) {
2480 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
2483 } else if (ObjCForwardProtocolDecl *ForwardProto
2484 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2485 for (ObjCForwardProtocolDecl::protocol_iterator
2486 P = ForwardProto->protocol_begin(),
2487 PEnd = ForwardProto->protocol_end();
2490 if (Result.isAcceptableDecl(*P)) {
2491 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2495 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2496 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2498 ObjCInterfaceDecl *IFace = I->getInterface();
2499 if (Result.isAcceptableDecl(IFace)) {
2500 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2506 // Visit transparent contexts and inline namespaces inside this context.
2507 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2508 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
2509 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
2515 // Traverse using directives for qualified name lookup.
2516 if (QualifiedNameLookup) {
2517 ShadowContextRAII Shadow(Visited);
2518 DeclContext::udir_iterator I, E;
2519 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2520 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
2521 QualifiedNameLookup, InBaseClass, Consumer, Visited);
2525 // Traverse the contexts of inherited C++ classes.
2526 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2527 if (!Record->hasDefinition())
2530 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2531 BEnd = Record->bases_end();
2533 QualType BaseType = B->getType();
2535 // Don't look into dependent bases, because name lookup can't look
2537 if (BaseType->isDependentType())
2540 const RecordType *Record = BaseType->getAs<RecordType>();
2544 // FIXME: It would be nice to be able to determine whether referencing
2545 // a particular member would be ambiguous. For example, given
2547 // struct A { int member; };
2548 // struct B { int member; };
2549 // struct C : A, B { };
2551 // void f(C *c) { c->### }
2553 // accessing 'member' would result in an ambiguity. However, we
2554 // could be smart enough to qualify the member with the base
2563 // Find results in this base class (and its bases).
2564 ShadowContextRAII Shadow(Visited);
2565 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2566 true, Consumer, Visited);
2570 // Traverse the contexts of Objective-C classes.
2571 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2572 // Traverse categories.
2573 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2574 Category; Category = Category->getNextClassCategory()) {
2575 ShadowContextRAII Shadow(Visited);
2576 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2580 // Traverse protocols.
2581 for (ObjCInterfaceDecl::all_protocol_iterator
2582 I = IFace->all_referenced_protocol_begin(),
2583 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
2584 ShadowContextRAII Shadow(Visited);
2585 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2589 // Traverse the superclass.
2590 if (IFace->getSuperClass()) {
2591 ShadowContextRAII Shadow(Visited);
2592 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
2593 true, Consumer, Visited);
2596 // If there is an implementation, traverse it. We do this to find
2597 // synthesized ivars.
2598 if (IFace->getImplementation()) {
2599 ShadowContextRAII Shadow(Visited);
2600 LookupVisibleDecls(IFace->getImplementation(), Result,
2601 QualifiedNameLookup, true, Consumer, Visited);
2603 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2604 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2605 E = Protocol->protocol_end(); I != E; ++I) {
2606 ShadowContextRAII Shadow(Visited);
2607 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2610 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2611 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2612 E = Category->protocol_end(); I != E; ++I) {
2613 ShadowContextRAII Shadow(Visited);
2614 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2618 // If there is an implementation, traverse it.
2619 if (Category->getImplementation()) {
2620 ShadowContextRAII Shadow(Visited);
2621 LookupVisibleDecls(Category->getImplementation(), Result,
2622 QualifiedNameLookup, true, Consumer, Visited);
2627 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2628 UnqualUsingDirectiveSet &UDirs,
2629 VisibleDeclConsumer &Consumer,
2630 VisibleDeclsRecord &Visited) {
2634 if (!S->getEntity() ||
2636 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
2637 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2638 // Walk through the declarations in this Scope.
2639 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2641 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2642 if (Result.isAcceptableDecl(ND)) {
2643 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
2649 // FIXME: C++ [temp.local]p8
2650 DeclContext *Entity = 0;
2651 if (S->getEntity()) {
2652 // Look into this scope's declaration context, along with any of its
2653 // parent lookup contexts (e.g., enclosing classes), up to the point
2654 // where we hit the context stored in the next outer scope.
2655 Entity = (DeclContext *)S->getEntity();
2656 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
2658 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
2659 Ctx = Ctx->getLookupParent()) {
2660 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2661 if (Method->isInstanceMethod()) {
2662 // For instance methods, look for ivars in the method's interface.
2663 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2664 Result.getNameLoc(), Sema::LookupMemberName);
2665 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
2666 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2667 /*InBaseClass=*/false, Consumer, Visited);
2669 // Look for properties from which we can synthesize ivars, if
2671 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2672 IFace->getImplementation() &&
2673 Result.getLookupKind() == Sema::LookupOrdinaryName) {
2674 for (ObjCInterfaceDecl::prop_iterator
2675 P = IFace->prop_begin(),
2676 PEnd = IFace->prop_end();
2678 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2679 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2680 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2688 // We've already performed all of the name lookup that we need
2689 // to for Objective-C methods; the next context will be the
2694 if (Ctx->isFunctionOrMethod())
2697 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
2698 /*InBaseClass=*/false, Consumer, Visited);
2700 } else if (!S->getParent()) {
2701 // Look into the translation unit scope. We walk through the translation
2702 // unit's declaration context, because the Scope itself won't have all of
2703 // the declarations if we loaded a precompiled header.
2704 // FIXME: We would like the translation unit's Scope object to point to the
2705 // translation unit, so we don't need this special "if" branch. However,
2706 // doing so would force the normal C++ name-lookup code to look into the
2707 // translation unit decl when the IdentifierInfo chains would suffice.
2708 // Once we fix that problem (which is part of a more general "don't look
2709 // in DeclContexts unless we have to" optimization), we can eliminate this.
2710 Entity = Result.getSema().Context.getTranslationUnitDecl();
2711 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
2712 /*InBaseClass=*/false, Consumer, Visited);
2716 // Lookup visible declarations in any namespaces found by using
2718 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2719 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2720 for (; UI != UEnd; ++UI)
2721 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
2722 Result, /*QualifiedNameLookup=*/false,
2723 /*InBaseClass=*/false, Consumer, Visited);
2726 // Lookup names in the parent scope.
2727 ShadowContextRAII Shadow(Visited);
2728 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2731 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2732 VisibleDeclConsumer &Consumer,
2733 bool IncludeGlobalScope) {
2734 // Determine the set of using directives available during
2735 // unqualified name lookup.
2737 UnqualUsingDirectiveSet UDirs;
2738 if (getLangOptions().CPlusPlus) {
2739 // Find the first namespace or translation-unit scope.
2740 while (S && !isNamespaceOrTranslationUnitScope(S))
2743 UDirs.visitScopeChain(Initial, S);
2747 // Look for visible declarations.
2748 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2749 VisibleDeclsRecord Visited;
2750 if (!IncludeGlobalScope)
2751 Visited.visitedContext(Context.getTranslationUnitDecl());
2752 ShadowContextRAII Shadow(Visited);
2753 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2756 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2757 VisibleDeclConsumer &Consumer,
2758 bool IncludeGlobalScope) {
2759 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2760 VisibleDeclsRecord Visited;
2761 if (!IncludeGlobalScope)
2762 Visited.visitedContext(Context.getTranslationUnitDecl());
2763 ShadowContextRAII Shadow(Visited);
2764 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2765 /*InBaseClass=*/false, Consumer, Visited);
2768 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
2769 /// If isLocalLabel is true, then this is a definition of an __label__ label
2770 /// name, otherwise it is a normal label definition or use.
2771 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
2772 bool isLocalLabel) {
2773 // Do a lookup to see if we have a label with this name already.
2776 // Local label definitions always shadow existing labels.
2778 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2780 // If we found a label, check to see if it is in the same context as us. When
2781 // in a Block, we don't want to reuse a label in an enclosing function.
2782 if (Res && Res->getDeclContext() != CurContext)
2786 // If not forward referenced or defined already, create the backing decl.
2787 Res = LabelDecl::Create(Context, CurContext, Loc, II);
2788 Scope *S = isLocalLabel ? CurScope : CurScope->getFnParent();
2789 assert(S && "Not in a function?");
2790 PushOnScopeChains(Res, S, true);
2793 return cast<LabelDecl>(Res);
2796 //===----------------------------------------------------------------------===//
2798 //===----------------------------------------------------------------------===//
2801 class TypoCorrectionConsumer : public VisibleDeclConsumer {
2802 /// \brief The name written that is a typo in the source.
2803 llvm::StringRef Typo;
2805 /// \brief The results found that have the smallest edit distance
2806 /// found (so far) with the typo name.
2808 /// The boolean value indicates whether there is a keyword with this name.
2809 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
2811 /// \brief The best edit distance found so far.
2812 unsigned BestEditDistance;
2815 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2816 : Typo(Typo->getName()),
2817 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
2819 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
2820 void FoundName(llvm::StringRef Name);
2821 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
2823 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2824 iterator begin() { return BestResults.begin(); }
2825 iterator end() { return BestResults.end(); }
2826 void erase(iterator I) { BestResults.erase(I); }
2827 unsigned size() const { return BestResults.size(); }
2828 bool empty() const { return BestResults.empty(); }
2830 bool &operator[](llvm::StringRef Name) {
2831 return BestResults[Name];
2834 unsigned getBestEditDistance() const { return BestEditDistance; }
2839 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2841 // Don't consider hidden names for typo correction.
2845 // Only consider entities with identifiers for names, ignoring
2846 // special names (constructors, overloaded operators, selectors,
2848 IdentifierInfo *Name = ND->getIdentifier();
2852 FoundName(Name->getName());
2855 void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
2856 using namespace std;
2858 // Use a simple length-based heuristic to determine the minimum possible
2859 // edit distance. If the minimum isn't good enough, bail out early.
2860 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2861 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2864 // Compute an upper bound on the allowable edit distance, so that the
2865 // edit-distance algorithm can short-circuit.
2866 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
2868 // Compute the edit distance between the typo and the name of this
2869 // entity. If this edit distance is not worse than the best edit
2870 // distance we've seen so far, add it to the list of results.
2871 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
2875 if (ED < BestEditDistance) {
2876 // This result is better than any we've seen before; clear out
2877 // the previous results.
2878 BestResults.clear();
2879 BestEditDistance = ED;
2880 } else if (ED > BestEditDistance) {
2881 // This result is worse than the best results we've seen so far;
2886 // Add this name to the list of results. By not assigning a value, we
2887 // keep the current value if we've seen this name before (either as a
2888 // keyword or as a declaration), or get the default value (not a keyword)
2889 // if we haven't seen it before.
2890 (void)BestResults[Name];
2893 void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2894 llvm::StringRef Keyword) {
2895 // Compute the edit distance between the typo and this keyword.
2896 // If this edit distance is not worse than the best edit
2897 // distance we've seen so far, add it to the list of results.
2898 unsigned ED = Typo.edit_distance(Keyword);
2899 if (ED < BestEditDistance) {
2900 BestResults.clear();
2901 BestEditDistance = ED;
2902 } else if (ED > BestEditDistance) {
2903 // This result is worse than the best results we've seen so far;
2908 BestResults[Keyword] = true;
2911 /// \brief Perform name lookup for a possible result for typo correction.
2912 static void LookupPotentialTypoResult(Sema &SemaRef,
2914 IdentifierInfo *Name,
2915 Scope *S, CXXScopeSpec *SS,
2916 DeclContext *MemberContext,
2917 bool EnteringContext,
2918 Sema::CorrectTypoContext CTC) {
2919 Res.suppressDiagnostics();
2921 Res.setLookupName(Name);
2922 if (MemberContext) {
2923 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2924 if (CTC == Sema::CTC_ObjCIvarLookup) {
2925 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2932 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2939 SemaRef.LookupQualifiedName(Res, MemberContext);
2943 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2946 // Fake ivar lookup; this should really be part of
2947 // LookupParsedName.
2948 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2949 if (Method->isInstanceMethod() && Method->getClassInterface() &&
2951 (Res.isSingleResult() &&
2952 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
2953 if (ObjCIvarDecl *IV
2954 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2962 /// \brief Try to "correct" a typo in the source code by finding
2963 /// visible declarations whose names are similar to the name that was
2964 /// present in the source code.
2966 /// \param Res the \c LookupResult structure that contains the name
2967 /// that was present in the source code along with the name-lookup
2968 /// criteria used to search for the name. On success, this structure
2969 /// will contain the results of name lookup.
2971 /// \param S the scope in which name lookup occurs.
2973 /// \param SS the nested-name-specifier that precedes the name we're
2974 /// looking for, if present.
2976 /// \param MemberContext if non-NULL, the context in which to look for
2977 /// a member access expression.
2979 /// \param EnteringContext whether we're entering the context described by
2980 /// the nested-name-specifier SS.
2982 /// \param CTC The context in which typo correction occurs, which impacts the
2983 /// set of keywords permitted.
2985 /// \param OPT when non-NULL, the search for visible declarations will
2986 /// also walk the protocols in the qualified interfaces of \p OPT.
2988 /// \returns the corrected name if the typo was corrected, otherwise returns an
2989 /// empty \c DeclarationName. When a typo was corrected, the result structure
2990 /// may contain the results of name lookup for the correct name or it may be
2992 DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
2993 DeclContext *MemberContext,
2994 bool EnteringContext,
2995 CorrectTypoContext CTC,
2996 const ObjCObjectPointerType *OPT) {
2997 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
2998 return DeclarationName();
3000 // We only attempt to correct typos for identifiers.
3001 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
3003 return DeclarationName();
3005 // If the scope specifier itself was invalid, don't try to correct
3007 if (SS && SS->isInvalid())
3008 return DeclarationName();
3010 // Never try to correct typos during template deduction or
3012 if (!ActiveTemplateInstantiations.empty())
3013 return DeclarationName();
3015 TypoCorrectionConsumer Consumer(Typo);
3017 // Perform name lookup to find visible, similarly-named entities.
3018 bool IsUnqualifiedLookup = false;
3019 if (MemberContext) {
3020 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
3022 // Look in qualified interfaces.
3024 for (ObjCObjectPointerType::qual_iterator
3025 I = OPT->qual_begin(), E = OPT->qual_end();
3027 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
3029 } else if (SS && SS->isSet()) {
3030 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3032 return DeclarationName();
3034 // Provide a stop gap for files that are just seriously broken. Trying
3035 // to correct all typos can turn into a HUGE performance penalty, causing
3036 // some files to take minutes to get rejected by the parser.
3037 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3038 return DeclarationName();
3041 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
3043 IsUnqualifiedLookup = true;
3044 UnqualifiedTyposCorrectedMap::iterator Cached
3045 = UnqualifiedTyposCorrected.find(Typo);
3046 if (Cached == UnqualifiedTyposCorrected.end()) {
3047 // Provide a stop gap for files that are just seriously broken. Trying
3048 // to correct all typos can turn into a HUGE performance penalty, causing
3049 // some files to take minutes to get rejected by the parser.
3050 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3051 return DeclarationName();
3053 // For unqualified lookup, look through all of the names that we have
3054 // seen in this translation unit.
3055 for (IdentifierTable::iterator I = Context.Idents.begin(),
3056 IEnd = Context.Idents.end();
3058 Consumer.FoundName(I->getKey());
3060 // Walk through identifiers in external identifier sources.
3061 if (IdentifierInfoLookup *External
3062 = Context.Idents.getExternalIdentifierLookup()) {
3063 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
3065 llvm::StringRef Name = Iter->Next();
3069 Consumer.FoundName(Name);
3073 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3074 // end up adding the keyword below.
3075 if (Cached->second.first.empty())
3076 return DeclarationName();
3078 if (!Cached->second.second)
3079 Consumer.FoundName(Cached->second.first);
3083 // Add context-dependent keywords.
3084 bool WantTypeSpecifiers = false;
3085 bool WantExpressionKeywords = false;
3086 bool WantCXXNamedCasts = false;
3087 bool WantRemainingKeywords = false;
3090 WantTypeSpecifiers = true;
3091 WantExpressionKeywords = true;
3092 WantCXXNamedCasts = true;
3093 WantRemainingKeywords = true;
3095 if (ObjCMethodDecl *Method = getCurMethodDecl())
3096 if (Method->getClassInterface() &&
3097 Method->getClassInterface()->getSuperClass())
3098 Consumer.addKeywordResult(Context, "super");
3102 case CTC_NoKeywords:
3106 WantTypeSpecifiers = true;
3109 case CTC_ObjCMessageReceiver:
3110 Consumer.addKeywordResult(Context, "super");
3111 // Fall through to handle message receivers like expressions.
3113 case CTC_Expression:
3114 if (getLangOptions().CPlusPlus)
3115 WantTypeSpecifiers = true;
3116 WantExpressionKeywords = true;
3117 // Fall through to get C++ named casts.
3120 WantCXXNamedCasts = true;
3123 case CTC_ObjCPropertyLookup:
3124 // FIXME: Add "isa"?
3127 case CTC_MemberLookup:
3128 if (getLangOptions().CPlusPlus)
3129 Consumer.addKeywordResult(Context, "template");
3132 case CTC_ObjCIvarLookup:
3136 if (WantTypeSpecifiers) {
3137 // Add type-specifier keywords to the set of results.
3138 const char *CTypeSpecs[] = {
3139 "char", "const", "double", "enum", "float", "int", "long", "short",
3140 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3141 "_Complex", "_Imaginary",
3142 // storage-specifiers as well
3143 "extern", "inline", "static", "typedef"
3146 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3147 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3148 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
3150 if (getLangOptions().C99)
3151 Consumer.addKeywordResult(Context, "restrict");
3152 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3153 Consumer.addKeywordResult(Context, "bool");
3155 if (getLangOptions().CPlusPlus) {
3156 Consumer.addKeywordResult(Context, "class");
3157 Consumer.addKeywordResult(Context, "typename");
3158 Consumer.addKeywordResult(Context, "wchar_t");
3160 if (getLangOptions().CPlusPlus0x) {
3161 Consumer.addKeywordResult(Context, "char16_t");
3162 Consumer.addKeywordResult(Context, "char32_t");
3163 Consumer.addKeywordResult(Context, "constexpr");
3164 Consumer.addKeywordResult(Context, "decltype");
3165 Consumer.addKeywordResult(Context, "thread_local");
3169 if (getLangOptions().GNUMode)
3170 Consumer.addKeywordResult(Context, "typeof");
3173 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
3174 Consumer.addKeywordResult(Context, "const_cast");
3175 Consumer.addKeywordResult(Context, "dynamic_cast");
3176 Consumer.addKeywordResult(Context, "reinterpret_cast");
3177 Consumer.addKeywordResult(Context, "static_cast");
3180 if (WantExpressionKeywords) {
3181 Consumer.addKeywordResult(Context, "sizeof");
3182 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3183 Consumer.addKeywordResult(Context, "false");
3184 Consumer.addKeywordResult(Context, "true");
3187 if (getLangOptions().CPlusPlus) {
3188 const char *CXXExprs[] = {
3189 "delete", "new", "operator", "throw", "typeid"
3191 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3192 for (unsigned I = 0; I != NumCXXExprs; ++I)
3193 Consumer.addKeywordResult(Context, CXXExprs[I]);
3195 if (isa<CXXMethodDecl>(CurContext) &&
3196 cast<CXXMethodDecl>(CurContext)->isInstance())
3197 Consumer.addKeywordResult(Context, "this");
3199 if (getLangOptions().CPlusPlus0x) {
3200 Consumer.addKeywordResult(Context, "alignof");
3201 Consumer.addKeywordResult(Context, "nullptr");
3206 if (WantRemainingKeywords) {
3207 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3209 const char *CStmts[] = {
3210 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3211 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3212 for (unsigned I = 0; I != NumCStmts; ++I)
3213 Consumer.addKeywordResult(Context, CStmts[I]);
3215 if (getLangOptions().CPlusPlus) {
3216 Consumer.addKeywordResult(Context, "catch");
3217 Consumer.addKeywordResult(Context, "try");
3220 if (S && S->getBreakParent())
3221 Consumer.addKeywordResult(Context, "break");
3223 if (S && S->getContinueParent())
3224 Consumer.addKeywordResult(Context, "continue");
3226 if (!getCurFunction()->SwitchStack.empty()) {
3227 Consumer.addKeywordResult(Context, "case");
3228 Consumer.addKeywordResult(Context, "default");
3231 if (getLangOptions().CPlusPlus) {
3232 Consumer.addKeywordResult(Context, "namespace");
3233 Consumer.addKeywordResult(Context, "template");
3236 if (S && S->isClassScope()) {
3237 Consumer.addKeywordResult(Context, "explicit");
3238 Consumer.addKeywordResult(Context, "friend");
3239 Consumer.addKeywordResult(Context, "mutable");
3240 Consumer.addKeywordResult(Context, "private");
3241 Consumer.addKeywordResult(Context, "protected");
3242 Consumer.addKeywordResult(Context, "public");
3243 Consumer.addKeywordResult(Context, "virtual");
3247 if (getLangOptions().CPlusPlus) {
3248 Consumer.addKeywordResult(Context, "using");
3250 if (getLangOptions().CPlusPlus0x)
3251 Consumer.addKeywordResult(Context, "static_assert");
3255 // If we haven't found anything, we're done.
3256 if (Consumer.empty()) {
3257 // If this was an unqualified lookup, note that no correction was found.
3258 if (IsUnqualifiedLookup)
3259 (void)UnqualifiedTyposCorrected[Typo];
3261 return DeclarationName();
3264 // Make sure that the user typed at least 3 characters for each correction
3265 // made. Otherwise, we don't even both looking at the results.
3267 // We also suppress exact matches; those should be handled by a
3268 // different mechanism (e.g., one that introduces qualification in
3270 unsigned ED = Consumer.getBestEditDistance();
3271 if (ED > 0 && Typo->getName().size() / ED < 3) {
3272 // If this was an unqualified lookup, note that no correction was found.
3273 if (IsUnqualifiedLookup)
3274 (void)UnqualifiedTyposCorrected[Typo];
3276 return DeclarationName();
3279 // Weed out any names that could not be found by name lookup.
3280 bool LastLookupWasAccepted = false;
3281 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3282 IEnd = Consumer.end();
3283 I != IEnd; /* Increment in loop. */) {
3284 // Keywords are always found.
3290 // Perform name lookup on this name.
3291 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
3292 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3293 EnteringContext, CTC);
3295 switch (Res.getResultKind()) {
3296 case LookupResult::NotFound:
3297 case LookupResult::NotFoundInCurrentInstantiation:
3298 case LookupResult::Ambiguous:
3299 // We didn't find this name in our scope, or didn't like what we found;
3301 Res.suppressDiagnostics();
3303 TypoCorrectionConsumer::iterator Next = I;
3308 LastLookupWasAccepted = false;
3311 case LookupResult::Found:
3312 case LookupResult::FoundOverloaded:
3313 case LookupResult::FoundUnresolvedValue:
3315 LastLookupWasAccepted = true;
3319 if (Res.isAmbiguous()) {
3320 // We don't deal with ambiguities.
3321 Res.suppressDiagnostics();
3323 return DeclarationName();
3327 // If only a single name remains, return that result.
3328 if (Consumer.size() == 1) {
3329 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
3330 if (Consumer.begin()->second) {
3331 Res.suppressDiagnostics();
3334 // Don't correct to a keyword that's the same as the typo; the keyword
3335 // wasn't actually in scope.
3337 Res.setLookupName(Typo);
3338 return DeclarationName();
3341 } else if (!LastLookupWasAccepted) {
3342 // Perform name lookup on this name.
3343 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3344 EnteringContext, CTC);
3347 // Record the correction for unqualified lookup.
3348 if (IsUnqualifiedLookup)
3349 UnqualifiedTyposCorrected[Typo]
3350 = std::make_pair(Name->getName(), Consumer.begin()->second);
3352 return &Context.Idents.get(Consumer.begin()->getKey());
3354 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
3355 && Consumer["super"]) {
3356 // Prefix 'super' when we're completing in a message-receiver
3358 Res.suppressDiagnostics();
3361 // Don't correct to a keyword that's the same as the typo; the keyword
3362 // wasn't actually in scope.
3364 Res.setLookupName(Typo);
3365 return DeclarationName();
3368 // Record the correction for unqualified lookup.
3369 if (IsUnqualifiedLookup)
3370 UnqualifiedTyposCorrected[Typo]
3371 = std::make_pair("super", Consumer.begin()->second);
3373 return &Context.Idents.get("super");
3376 Res.suppressDiagnostics();
3377 Res.setLookupName(Typo);
3379 // Record the correction for unqualified lookup.
3380 if (IsUnqualifiedLookup)
3381 (void)UnqualifiedTyposCorrected[Typo];
3383 return DeclarationName();