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.ExceptionSpecType = EST_None;
690 EPI.NumExceptions = 0;
691 QualType ExpectedType
692 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
695 // Perform template argument deduction against the type that we would
696 // expect the function to have.
697 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
698 Specialization, Info)
699 == Sema::TDK_Success) {
700 R.addDecl(Specialization);
708 // Performs C++ unqualified lookup into the given file context.
710 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
711 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
713 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
715 // Perform direct name lookup into the LookupCtx.
716 bool Found = LookupDirect(S, R, NS);
718 // Perform direct name lookup into the namespaces nominated by the
719 // using directives whose common ancestor is this namespace.
720 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
721 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
723 for (; UI != UEnd; ++UI)
724 if (LookupDirect(S, R, UI->getNominatedNamespace()))
732 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
733 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
734 return Ctx->isFileContext();
738 // Find the next outer declaration context from this scope. This
739 // routine actually returns the semantic outer context, which may
740 // differ from the lexical context (encoded directly in the Scope
741 // stack) when we are parsing a member of a class template. In this
742 // case, the second element of the pair will be true, to indicate that
743 // name lookup should continue searching in this semantic context when
744 // it leaves the current template parameter scope.
745 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
746 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
747 DeclContext *Lexical = 0;
748 for (Scope *OuterS = S->getParent(); OuterS;
749 OuterS = OuterS->getParent()) {
750 if (OuterS->getEntity()) {
751 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
756 // C++ [temp.local]p8:
757 // In the definition of a member of a class template that appears
758 // outside of the namespace containing the class template
759 // definition, the name of a template-parameter hides the name of
760 // a member of this namespace.
767 // template<class T> class B {
772 // template<class C> void N::B<C>::f(C) {
773 // C b; // C is the template parameter, not N::C
776 // In this example, the lexical context we return is the
777 // TranslationUnit, while the semantic context is the namespace N.
778 if (!Lexical || !DC || !S->getParent() ||
779 !S->getParent()->isTemplateParamScope())
780 return std::make_pair(Lexical, false);
782 // Find the outermost template parameter scope.
783 // For the example, this is the scope for the template parameters of
784 // template<class C>.
785 Scope *OutermostTemplateScope = S->getParent();
786 while (OutermostTemplateScope->getParent() &&
787 OutermostTemplateScope->getParent()->isTemplateParamScope())
788 OutermostTemplateScope = OutermostTemplateScope->getParent();
790 // Find the namespace context in which the original scope occurs. In
791 // the example, this is namespace N.
792 DeclContext *Semantic = DC;
793 while (!Semantic->isFileContext())
794 Semantic = Semantic->getParent();
796 // Find the declaration context just outside of the template
797 // parameter scope. This is the context in which the template is
798 // being lexically declaration (a namespace context). In the
799 // example, this is the global scope.
800 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
801 Lexical->Encloses(Semantic))
802 return std::make_pair(Semantic, true);
804 return std::make_pair(Lexical, false);
807 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
808 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
810 DeclarationName Name = R.getLookupName();
812 // If this is the name of an implicitly-declared special member function,
813 // go through the scope stack to implicitly declare
814 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
815 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
816 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
817 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
820 // Implicitly declare member functions with the name we're looking for, if in
821 // fact we are in a scope where it matters.
824 IdentifierResolver::iterator
825 I = IdResolver.begin(Name),
826 IEnd = IdResolver.end();
828 // First we lookup local scope.
829 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
830 // ...During unqualified name lookup (3.4.1), the names appear as if
831 // they were declared in the nearest enclosing namespace which contains
832 // both the using-directive and the nominated namespace.
833 // [Note: in this context, "contains" means "contains directly or
837 // namespace A { int i; }
841 // using namespace A;
842 // ++i; // finds local 'i', A::i appears at global scope
846 DeclContext *OutsideOfTemplateParamDC = 0;
847 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
848 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
850 // Check whether the IdResolver has anything in this scope.
852 for (; I != IEnd && S->isDeclScope(*I); ++I) {
853 if (R.isAcceptableDecl(*I)) {
860 if (S->isClassScope())
861 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
862 R.setNamingClass(Record);
866 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
867 S->getParent() && !S->getParent()->isTemplateParamScope()) {
868 // We've just searched the last template parameter scope and
869 // found nothing, so look into the the contexts between the
870 // lexical and semantic declaration contexts returned by
871 // findOuterContext(). This implements the name lookup behavior
872 // of C++ [temp.local]p8.
873 Ctx = OutsideOfTemplateParamDC;
874 OutsideOfTemplateParamDC = 0;
878 DeclContext *OuterCtx;
879 bool SearchAfterTemplateScope;
880 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
881 if (SearchAfterTemplateScope)
882 OutsideOfTemplateParamDC = OuterCtx;
884 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
885 // We do not directly look into transparent contexts, since
886 // those entities will be found in the nearest enclosing
887 // non-transparent context.
888 if (Ctx->isTransparentContext())
891 // We do not look directly into function or method contexts,
892 // since all of the local variables and parameters of the
893 // function/method are present within the Scope.
894 if (Ctx->isFunctionOrMethod()) {
895 // If we have an Objective-C instance method, look for ivars
896 // in the corresponding interface.
897 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
898 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
899 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
900 ObjCInterfaceDecl *ClassDeclared;
901 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
902 Name.getAsIdentifierInfo(),
904 if (R.isAcceptableDecl(Ivar)) {
916 // Perform qualified name lookup into this context.
917 // FIXME: In some cases, we know that every name that could be found by
918 // this qualified name lookup will also be on the identifier chain. For
919 // example, inside a class without any base classes, we never need to
920 // perform qualified lookup because all of the members are on top of the
922 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
928 // Stop if we ran out of scopes.
929 // FIXME: This really, really shouldn't be happening.
930 if (!S) return false;
932 // If we are looking for members, no need to look into global/namespace scope.
933 if (R.getLookupKind() == LookupMemberName)
936 // Collect UsingDirectiveDecls in all scopes, and recursively all
937 // nominated namespaces by those using-directives.
939 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
940 // don't build it for each lookup!
942 UnqualUsingDirectiveSet UDirs;
943 UDirs.visitScopeChain(Initial, S);
946 // Lookup namespace scope, and global scope.
947 // Unqualified name lookup in C++ requires looking into scopes
948 // that aren't strictly lexical, and therefore we walk through the
949 // context as well as walking through the scopes.
951 for (; S; S = S->getParent()) {
952 // Check whether the IdResolver has anything in this scope.
954 for (; I != IEnd && S->isDeclScope(*I); ++I) {
955 if (R.isAcceptableDecl(*I)) {
956 // We found something. Look for anything else in our scope
957 // with this same name and in an acceptable identifier
958 // namespace, so that we can construct an overload set if we
965 if (Found && S->isTemplateParamScope()) {
970 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
971 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
972 S->getParent() && !S->getParent()->isTemplateParamScope()) {
973 // We've just searched the last template parameter scope and
974 // found nothing, so look into the the contexts between the
975 // lexical and semantic declaration contexts returned by
976 // findOuterContext(). This implements the name lookup behavior
977 // of C++ [temp.local]p8.
978 Ctx = OutsideOfTemplateParamDC;
979 OutsideOfTemplateParamDC = 0;
983 DeclContext *OuterCtx;
984 bool SearchAfterTemplateScope;
985 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
986 if (SearchAfterTemplateScope)
987 OutsideOfTemplateParamDC = OuterCtx;
989 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
990 // We do not directly look into transparent contexts, since
991 // those entities will be found in the nearest enclosing
992 // non-transparent context.
993 if (Ctx->isTransparentContext())
996 // If we have a context, and it's not a context stashed in the
997 // template parameter scope for an out-of-line definition, also
998 // look into that context.
999 if (!(Found && S && S->isTemplateParamScope())) {
1000 assert(Ctx->isFileContext() &&
1001 "We should have been looking only at file context here already.");
1003 // Look into context considering using-directives.
1004 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1013 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1018 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1025 /// @brief Perform unqualified name lookup starting from a given
1028 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1029 /// used to find names within the current scope. For example, 'x' in
1033 /// return x; // unqualified name look finds 'x' in the global scope
1037 /// Different lookup criteria can find different names. For example, a
1038 /// particular scope can have both a struct and a function of the same
1039 /// name, and each can be found by certain lookup criteria. For more
1040 /// information about lookup criteria, see the documentation for the
1041 /// class LookupCriteria.
1043 /// @param S The scope from which unqualified name lookup will
1044 /// begin. If the lookup criteria permits, name lookup may also search
1045 /// in the parent scopes.
1047 /// @param Name The name of the entity that we are searching for.
1049 /// @param Loc If provided, the source location where we're performing
1050 /// name lookup. At present, this is only used to produce diagnostics when
1051 /// C library functions (like "malloc") are implicitly declared.
1053 /// @returns The result of name lookup, which includes zero or more
1054 /// declarations and possibly additional information used to diagnose
1056 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1057 DeclarationName Name = R.getLookupName();
1058 if (!Name) return false;
1060 LookupNameKind NameKind = R.getLookupKind();
1062 if (!getLangOptions().CPlusPlus) {
1063 // Unqualified name lookup in C/Objective-C is purely lexical, so
1064 // search in the declarations attached to the name.
1065 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1066 // Find the nearest non-transparent declaration scope.
1067 while (!(S->getFlags() & Scope::DeclScope) ||
1069 static_cast<DeclContext *>(S->getEntity())
1070 ->isTransparentContext()))
1074 unsigned IDNS = R.getIdentifierNamespace();
1076 // Scan up the scope chain looking for a decl that matches this
1077 // identifier that is in the appropriate namespace. This search
1078 // should not take long, as shadowing of names is uncommon, and
1079 // deep shadowing is extremely uncommon.
1080 bool LeftStartingScope = false;
1082 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1083 IEnd = IdResolver.end();
1085 if ((*I)->isInIdentifierNamespace(IDNS)) {
1086 if (NameKind == LookupRedeclarationWithLinkage) {
1087 // Determine whether this (or a previous) declaration is
1089 if (!LeftStartingScope && !S->isDeclScope(*I))
1090 LeftStartingScope = true;
1092 // If we found something outside of our starting scope that
1093 // does not have linkage, skip it.
1094 if (LeftStartingScope && !((*I)->hasLinkage()))
1100 if ((*I)->getAttr<OverloadableAttr>()) {
1101 // If this declaration has the "overloadable" attribute, we
1102 // might have a set of overloaded functions.
1104 // Figure out what scope the identifier is in.
1105 while (!(S->getFlags() & Scope::DeclScope) ||
1106 !S->isDeclScope(*I))
1109 // Find the last declaration in this scope (with the same
1110 // name, naturally).
1111 IdentifierResolver::iterator LastI = I;
1112 for (++LastI; LastI != IEnd; ++LastI) {
1113 if (!S->isDeclScope(*LastI))
1124 // Perform C++ unqualified name lookup.
1125 if (CppLookupName(R, S))
1129 // If we didn't find a use of this identifier, and if the identifier
1130 // corresponds to a compiler builtin, create the decl object for the builtin
1131 // now, injecting it into translation unit scope, and return it.
1132 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1135 // If we didn't find a use of this identifier, the ExternalSource
1136 // may be able to handle the situation.
1137 // Note: some lookup failures are expected!
1138 // See e.g. R.isForRedeclaration().
1139 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1142 /// @brief Perform qualified name lookup in the namespaces nominated by
1143 /// using directives by the given context.
1145 /// C++98 [namespace.qual]p2:
1146 /// Given X::m (where X is a user-declared namespace), or given ::m
1147 /// (where X is the global namespace), let S be the set of all
1148 /// declarations of m in X and in the transitive closure of all
1149 /// namespaces nominated by using-directives in X and its used
1150 /// namespaces, except that using-directives are ignored in any
1151 /// namespace, including X, directly containing one or more
1152 /// declarations of m. No namespace is searched more than once in
1153 /// the lookup of a name. If S is the empty set, the program is
1154 /// ill-formed. Otherwise, if S has exactly one member, or if the
1155 /// context of the reference is a using-declaration
1156 /// (namespace.udecl), S is the required set of declarations of
1157 /// m. Otherwise if the use of m is not one that allows a unique
1158 /// declaration to be chosen from S, the program is ill-formed.
1159 /// C++98 [namespace.qual]p5:
1160 /// During the lookup of a qualified namespace member name, if the
1161 /// lookup finds more than one declaration of the member, and if one
1162 /// declaration introduces a class name or enumeration name and the
1163 /// other declarations either introduce the same object, the same
1164 /// enumerator or a set of functions, the non-type name hides the
1165 /// class or enumeration name if and only if the declarations are
1166 /// from the same namespace; otherwise (the declarations are from
1167 /// different namespaces), the program is ill-formed.
1168 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1169 DeclContext *StartDC) {
1170 assert(StartDC->isFileContext() && "start context is not a file context");
1172 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1173 DeclContext::udir_iterator E = StartDC->using_directives_end();
1175 if (I == E) return false;
1177 // We have at least added all these contexts to the queue.
1178 llvm::DenseSet<DeclContext*> Visited;
1179 Visited.insert(StartDC);
1181 // We have not yet looked into these namespaces, much less added
1182 // their "using-children" to the queue.
1183 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1185 // We have already looked into the initial namespace; seed the queue
1186 // with its using-children.
1187 for (; I != E; ++I) {
1188 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1189 if (Visited.insert(ND).second)
1190 Queue.push_back(ND);
1193 // The easiest way to implement the restriction in [namespace.qual]p5
1194 // is to check whether any of the individual results found a tag
1195 // and, if so, to declare an ambiguity if the final result is not
1197 bool FoundTag = false;
1198 bool FoundNonTag = false;
1200 LookupResult LocalR(LookupResult::Temporary, R);
1203 while (!Queue.empty()) {
1204 NamespaceDecl *ND = Queue.back();
1207 // We go through some convolutions here to avoid copying results
1208 // between LookupResults.
1209 bool UseLocal = !R.empty();
1210 LookupResult &DirectR = UseLocal ? LocalR : R;
1211 bool FoundDirect = LookupDirect(S, DirectR, ND);
1214 // First do any local hiding.
1215 DirectR.resolveKind();
1217 // If the local result is a tag, remember that.
1218 if (DirectR.isSingleTagDecl())
1223 // Append the local results to the total results if necessary.
1225 R.addAllDecls(LocalR);
1230 // If we find names in this namespace, ignore its using directives.
1236 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1237 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1238 if (Visited.insert(Nom).second)
1239 Queue.push_back(Nom);
1244 if (FoundTag && FoundNonTag)
1245 R.setAmbiguousQualifiedTagHiding();
1253 /// \brief Callback that looks for any member of a class with the given name.
1254 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1257 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1259 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1260 Path.Decls = BaseRecord->lookup(N);
1261 return Path.Decls.first != Path.Decls.second;
1264 /// \brief Determine whether the given set of member declarations contains only
1265 /// static members, nested types, and enumerators.
1266 template<typename InputIterator>
1267 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1268 Decl *D = (*First)->getUnderlyingDecl();
1269 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1272 if (isa<CXXMethodDecl>(D)) {
1273 // Determine whether all of the methods are static.
1274 bool AllMethodsAreStatic = true;
1275 for(; First != Last; ++First) {
1276 D = (*First)->getUnderlyingDecl();
1278 if (!isa<CXXMethodDecl>(D)) {
1279 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1283 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1284 AllMethodsAreStatic = false;
1289 if (AllMethodsAreStatic)
1296 /// \brief Perform qualified name lookup into a given context.
1298 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1299 /// names when the context of those names is explicit specified, e.g.,
1300 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1302 /// Different lookup criteria can find different names. For example, a
1303 /// particular scope can have both a struct and a function of the same
1304 /// name, and each can be found by certain lookup criteria. For more
1305 /// information about lookup criteria, see the documentation for the
1306 /// class LookupCriteria.
1308 /// \param R captures both the lookup criteria and any lookup results found.
1310 /// \param LookupCtx The context in which qualified name lookup will
1311 /// search. If the lookup criteria permits, name lookup may also search
1312 /// in the parent contexts or (for C++ classes) base classes.
1314 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1315 /// occurs as part of unqualified name lookup.
1317 /// \returns true if lookup succeeded, false if it failed.
1318 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1319 bool InUnqualifiedLookup) {
1320 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1322 if (!R.getLookupName())
1325 // Make sure that the declaration context is complete.
1326 assert((!isa<TagDecl>(LookupCtx) ||
1327 LookupCtx->isDependentContext() ||
1328 cast<TagDecl>(LookupCtx)->isDefinition() ||
1329 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1330 ->isBeingDefined()) &&
1331 "Declaration context must already be complete!");
1333 // Perform qualified name lookup into the LookupCtx.
1334 if (LookupDirect(*this, R, LookupCtx)) {
1336 if (isa<CXXRecordDecl>(LookupCtx))
1337 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1341 // Don't descend into implied contexts for redeclarations.
1342 // C++98 [namespace.qual]p6:
1343 // In a declaration for a namespace member in which the
1344 // declarator-id is a qualified-id, given that the qualified-id
1345 // for the namespace member has the form
1346 // nested-name-specifier unqualified-id
1347 // the unqualified-id shall name a member of the namespace
1348 // designated by the nested-name-specifier.
1349 // See also [class.mfct]p5 and [class.static.data]p2.
1350 if (R.isForRedeclaration())
1353 // If this is a namespace, look it up in the implied namespaces.
1354 if (LookupCtx->isFileContext())
1355 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1357 // If this isn't a C++ class, we aren't allowed to look into base
1358 // classes, we're done.
1359 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1360 if (!LookupRec || !LookupRec->getDefinition())
1363 // If we're performing qualified name lookup into a dependent class,
1364 // then we are actually looking into a current instantiation. If we have any
1365 // dependent base classes, then we either have to delay lookup until
1366 // template instantiation time (at which point all bases will be available)
1367 // or we have to fail.
1368 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1369 LookupRec->hasAnyDependentBases()) {
1370 R.setNotFoundInCurrentInstantiation();
1374 // Perform lookup into our base classes.
1376 Paths.setOrigin(LookupRec);
1378 // Look for this member in our base classes
1379 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1380 switch (R.getLookupKind()) {
1381 case LookupOrdinaryName:
1382 case LookupMemberName:
1383 case LookupRedeclarationWithLinkage:
1384 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1388 BaseCallback = &CXXRecordDecl::FindTagMember;
1392 BaseCallback = &LookupAnyMember;
1395 case LookupUsingDeclName:
1396 // This lookup is for redeclarations only.
1398 case LookupOperatorName:
1399 case LookupNamespaceName:
1400 case LookupObjCProtocolName:
1402 // These lookups will never find a member in a C++ class (or base class).
1405 case LookupNestedNameSpecifierName:
1406 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1410 if (!LookupRec->lookupInBases(BaseCallback,
1411 R.getLookupName().getAsOpaquePtr(), Paths))
1414 R.setNamingClass(LookupRec);
1416 // C++ [class.member.lookup]p2:
1417 // [...] If the resulting set of declarations are not all from
1418 // sub-objects of the same type, or the set has a nonstatic member
1419 // and includes members from distinct sub-objects, there is an
1420 // ambiguity and the program is ill-formed. Otherwise that set is
1421 // the result of the lookup.
1422 QualType SubobjectType;
1423 int SubobjectNumber = 0;
1424 AccessSpecifier SubobjectAccess = AS_none;
1426 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1427 Path != PathEnd; ++Path) {
1428 const CXXBasePathElement &PathElement = Path->back();
1430 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1431 // across all paths.
1432 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1434 // Determine whether we're looking at a distinct sub-object or not.
1435 if (SubobjectType.isNull()) {
1436 // This is the first subobject we've looked at. Record its type.
1437 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1438 SubobjectNumber = PathElement.SubobjectNumber;
1443 != Context.getCanonicalType(PathElement.Base->getType())) {
1444 // We found members of the given name in two subobjects of
1445 // different types. If the declaration sets aren't the same, this
1446 // this lookup is ambiguous.
1447 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1448 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1449 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1450 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1452 while (FirstD != FirstPath->Decls.second &&
1453 CurrentD != Path->Decls.second) {
1454 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1455 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1462 if (FirstD == FirstPath->Decls.second &&
1463 CurrentD == Path->Decls.second)
1467 R.setAmbiguousBaseSubobjectTypes(Paths);
1471 if (SubobjectNumber != PathElement.SubobjectNumber) {
1472 // We have a different subobject of the same type.
1474 // C++ [class.member.lookup]p5:
1475 // A static member, a nested type or an enumerator defined in
1476 // a base class T can unambiguously be found even if an object
1477 // has more than one base class subobject of type T.
1478 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
1481 // We have found a nonstatic member name in multiple, distinct
1482 // subobjects. Name lookup is ambiguous.
1483 R.setAmbiguousBaseSubobjects(Paths);
1488 // Lookup in a base class succeeded; return these results.
1490 DeclContext::lookup_iterator I, E;
1491 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1493 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1501 /// @brief Performs name lookup for a name that was parsed in the
1502 /// source code, and may contain a C++ scope specifier.
1504 /// This routine is a convenience routine meant to be called from
1505 /// contexts that receive a name and an optional C++ scope specifier
1506 /// (e.g., "N::M::x"). It will then perform either qualified or
1507 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1508 /// respectively) on the given name and return those results.
1510 /// @param S The scope from which unqualified name lookup will
1513 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1515 /// @param EnteringContext Indicates whether we are going to enter the
1516 /// context of the scope-specifier SS (if present).
1518 /// @returns True if any decls were found (but possibly ambiguous)
1519 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1520 bool AllowBuiltinCreation, bool EnteringContext) {
1521 if (SS && SS->isInvalid()) {
1522 // When the scope specifier is invalid, don't even look for
1527 if (SS && SS->isSet()) {
1528 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1529 // We have resolved the scope specifier to a particular declaration
1530 // contex, and will perform name lookup in that context.
1531 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1534 R.setContextRange(SS->getRange());
1536 return LookupQualifiedName(R, DC);
1539 // We could not resolve the scope specified to a specific declaration
1540 // context, which means that SS refers to an unknown specialization.
1541 // Name lookup can't find anything in this case.
1545 // Perform unqualified name lookup starting in the given scope.
1546 return LookupName(R, S, AllowBuiltinCreation);
1550 /// @brief Produce a diagnostic describing the ambiguity that resulted
1551 /// from name lookup.
1553 /// @param Result The ambiguous name lookup result.
1555 /// @param Name The name of the entity that name lookup was
1558 /// @param NameLoc The location of the name within the source code.
1560 /// @param LookupRange A source range that provides more
1561 /// source-location information concerning the lookup itself. For
1562 /// example, this range might highlight a nested-name-specifier that
1563 /// precedes the name.
1566 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1567 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1569 DeclarationName Name = Result.getLookupName();
1570 SourceLocation NameLoc = Result.getNameLoc();
1571 SourceRange LookupRange = Result.getContextRange();
1573 switch (Result.getAmbiguityKind()) {
1574 case LookupResult::AmbiguousBaseSubobjects: {
1575 CXXBasePaths *Paths = Result.getBasePaths();
1576 QualType SubobjectType = Paths->front().back().Base->getType();
1577 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1578 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1581 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1582 while (isa<CXXMethodDecl>(*Found) &&
1583 cast<CXXMethodDecl>(*Found)->isStatic())
1586 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1591 case LookupResult::AmbiguousBaseSubobjectTypes: {
1592 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1593 << Name << LookupRange;
1595 CXXBasePaths *Paths = Result.getBasePaths();
1596 std::set<Decl *> DeclsPrinted;
1597 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1598 PathEnd = Paths->end();
1599 Path != PathEnd; ++Path) {
1600 Decl *D = *Path->Decls.first;
1601 if (DeclsPrinted.insert(D).second)
1602 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1608 case LookupResult::AmbiguousTagHiding: {
1609 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1611 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1613 LookupResult::iterator DI, DE = Result.end();
1614 for (DI = Result.begin(); DI != DE; ++DI)
1615 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1616 TagDecls.insert(TD);
1617 Diag(TD->getLocation(), diag::note_hidden_tag);
1620 for (DI = Result.begin(); DI != DE; ++DI)
1621 if (!isa<TagDecl>(*DI))
1622 Diag((*DI)->getLocation(), diag::note_hiding_object);
1624 // For recovery purposes, go ahead and implement the hiding.
1625 LookupResult::Filter F = Result.makeFilter();
1626 while (F.hasNext()) {
1627 if (TagDecls.count(F.next()))
1635 case LookupResult::AmbiguousReference: {
1636 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1638 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1639 for (; DI != DE; ++DI)
1640 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1646 llvm_unreachable("unknown ambiguity kind");
1651 struct AssociatedLookup {
1652 AssociatedLookup(Sema &S,
1653 Sema::AssociatedNamespaceSet &Namespaces,
1654 Sema::AssociatedClassSet &Classes)
1655 : S(S), Namespaces(Namespaces), Classes(Classes) {
1659 Sema::AssociatedNamespaceSet &Namespaces;
1660 Sema::AssociatedClassSet &Classes;
1665 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1667 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1669 // Add the associated namespace for this class.
1671 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1672 // be a locally scoped record.
1674 // We skip out of inline namespaces. The innermost non-inline namespace
1675 // contains all names of all its nested inline namespaces anyway, so we can
1676 // replace the entire inline namespace tree with its root.
1677 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1678 Ctx->isInlineNamespace())
1679 Ctx = Ctx->getParent();
1681 if (Ctx->isFileContext())
1682 Namespaces.insert(Ctx->getPrimaryContext());
1685 // \brief Add the associated classes and namespaces for argument-dependent
1686 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1688 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1689 const TemplateArgument &Arg) {
1690 // C++ [basic.lookup.koenig]p2, last bullet:
1692 switch (Arg.getKind()) {
1693 case TemplateArgument::Null:
1696 case TemplateArgument::Type:
1697 // [...] the namespaces and classes associated with the types of the
1698 // template arguments provided for template type parameters (excluding
1699 // template template parameters)
1700 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1703 case TemplateArgument::Template:
1704 case TemplateArgument::TemplateExpansion: {
1705 // [...] the namespaces in which any template template arguments are
1706 // defined; and the classes in which any member templates used as
1707 // template template arguments are defined.
1708 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1709 if (ClassTemplateDecl *ClassTemplate
1710 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1711 DeclContext *Ctx = ClassTemplate->getDeclContext();
1712 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1713 Result.Classes.insert(EnclosingClass);
1714 // Add the associated namespace for this class.
1715 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1720 case TemplateArgument::Declaration:
1721 case TemplateArgument::Integral:
1722 case TemplateArgument::Expression:
1723 // [Note: non-type template arguments do not contribute to the set of
1724 // associated namespaces. ]
1727 case TemplateArgument::Pack:
1728 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1729 PEnd = Arg.pack_end();
1731 addAssociatedClassesAndNamespaces(Result, *P);
1736 // \brief Add the associated classes and namespaces for
1737 // argument-dependent lookup with an argument of class type
1738 // (C++ [basic.lookup.koenig]p2).
1740 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1741 CXXRecordDecl *Class) {
1743 // Just silently ignore anything whose name is __va_list_tag.
1744 if (Class->getDeclName() == Result.S.VAListTagName)
1747 // C++ [basic.lookup.koenig]p2:
1749 // -- If T is a class type (including unions), its associated
1750 // classes are: the class itself; the class of which it is a
1751 // member, if any; and its direct and indirect base
1752 // classes. Its associated namespaces are the namespaces in
1753 // which its associated classes are defined.
1755 // Add the class of which it is a member, if any.
1756 DeclContext *Ctx = Class->getDeclContext();
1757 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1758 Result.Classes.insert(EnclosingClass);
1759 // Add the associated namespace for this class.
1760 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1762 // Add the class itself. If we've already seen this class, we don't
1763 // need to visit base classes.
1764 if (!Result.Classes.insert(Class))
1767 // -- If T is a template-id, its associated namespaces and classes are
1768 // the namespace in which the template is defined; for member
1769 // templates, the member template's class; the namespaces and classes
1770 // associated with the types of the template arguments provided for
1771 // template type parameters (excluding template template parameters); the
1772 // namespaces in which any template template arguments are defined; and
1773 // the classes in which any member templates used as template template
1774 // arguments are defined. [Note: non-type template arguments do not
1775 // contribute to the set of associated namespaces. ]
1776 if (ClassTemplateSpecializationDecl *Spec
1777 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1778 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1779 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1780 Result.Classes.insert(EnclosingClass);
1781 // Add the associated namespace for this class.
1782 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1784 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1785 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1786 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
1789 // Only recurse into base classes for complete types.
1790 if (!Class->hasDefinition()) {
1791 // FIXME: we might need to instantiate templates here
1795 // Add direct and indirect base classes along with their associated
1797 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1798 Bases.push_back(Class);
1799 while (!Bases.empty()) {
1800 // Pop this class off the stack.
1801 Class = Bases.back();
1804 // Visit the base classes.
1805 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1806 BaseEnd = Class->bases_end();
1807 Base != BaseEnd; ++Base) {
1808 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1809 // In dependent contexts, we do ADL twice, and the first time around,
1810 // the base type might be a dependent TemplateSpecializationType, or a
1811 // TemplateTypeParmType. If that happens, simply ignore it.
1812 // FIXME: If we want to support export, we probably need to add the
1813 // namespace of the template in a TemplateSpecializationType, or even
1814 // the classes and namespaces of known non-dependent arguments.
1817 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1818 if (Result.Classes.insert(BaseDecl)) {
1819 // Find the associated namespace for this base class.
1820 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1821 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
1823 // Make sure we visit the bases of this base class.
1824 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1825 Bases.push_back(BaseDecl);
1831 // \brief Add the associated classes and namespaces for
1832 // argument-dependent lookup with an argument of type T
1833 // (C++ [basic.lookup.koenig]p2).
1835 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
1836 // C++ [basic.lookup.koenig]p2:
1838 // For each argument type T in the function call, there is a set
1839 // of zero or more associated namespaces and a set of zero or more
1840 // associated classes to be considered. The sets of namespaces and
1841 // classes is determined entirely by the types of the function
1842 // arguments (and the namespace of any template template
1843 // argument). Typedef names and using-declarations used to specify
1844 // the types do not contribute to this set. The sets of namespaces
1845 // and classes are determined in the following way:
1847 llvm::SmallVector<const Type *, 16> Queue;
1848 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1851 switch (T->getTypeClass()) {
1853 #define TYPE(Class, Base)
1854 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1855 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1856 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1857 #define ABSTRACT_TYPE(Class, Base)
1858 #include "clang/AST/TypeNodes.def"
1859 // T is canonical. We can also ignore dependent types because
1860 // we don't need to do ADL at the definition point, but if we
1861 // wanted to implement template export (or if we find some other
1862 // use for associated classes and namespaces...) this would be
1866 // -- If T is a pointer to U or an array of U, its associated
1867 // namespaces and classes are those associated with U.
1869 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1871 case Type::ConstantArray:
1872 case Type::IncompleteArray:
1873 case Type::VariableArray:
1874 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1877 // -- If T is a fundamental type, its associated sets of
1878 // namespaces and classes are both empty.
1882 // -- If T is a class type (including unions), its associated
1883 // classes are: the class itself; the class of which it is a
1884 // member, if any; and its direct and indirect base
1885 // classes. Its associated namespaces are the namespaces in
1886 // which its associated classes are defined.
1887 case Type::Record: {
1888 CXXRecordDecl *Class
1889 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
1890 addAssociatedClassesAndNamespaces(Result, Class);
1894 // -- If T is an enumeration type, its associated namespace is
1895 // the namespace in which it is defined. If it is class
1896 // member, its associated class is the member's class; else
1897 // it has no associated class.
1899 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
1901 DeclContext *Ctx = Enum->getDeclContext();
1902 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1903 Result.Classes.insert(EnclosingClass);
1905 // Add the associated namespace for this class.
1906 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1911 // -- If T is a function type, its associated namespaces and
1912 // classes are those associated with the function parameter
1913 // types and those associated with the return type.
1914 case Type::FunctionProto: {
1915 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1916 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1917 ArgEnd = Proto->arg_type_end();
1918 Arg != ArgEnd; ++Arg)
1919 Queue.push_back(Arg->getTypePtr());
1922 case Type::FunctionNoProto: {
1923 const FunctionType *FnType = cast<FunctionType>(T);
1924 T = FnType->getResultType().getTypePtr();
1928 // -- If T is a pointer to a member function of a class X, its
1929 // associated namespaces and classes are those associated
1930 // with the function parameter types and return type,
1931 // together with those associated with X.
1933 // -- If T is a pointer to a data member of class X, its
1934 // associated namespaces and classes are those associated
1935 // with the member type together with those associated with
1937 case Type::MemberPointer: {
1938 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1940 // Queue up the class type into which this points.
1941 Queue.push_back(MemberPtr->getClass());
1943 // And directly continue with the pointee type.
1944 T = MemberPtr->getPointeeType().getTypePtr();
1948 // As an extension, treat this like a normal pointer.
1949 case Type::BlockPointer:
1950 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1953 // References aren't covered by the standard, but that's such an
1954 // obvious defect that we cover them anyway.
1955 case Type::LValueReference:
1956 case Type::RValueReference:
1957 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1960 // These are fundamental types.
1962 case Type::ExtVector:
1966 // If T is an Objective-C object or interface type, or a pointer to an
1967 // object or interface type, the associated namespace is the global
1969 case Type::ObjCObject:
1970 case Type::ObjCInterface:
1971 case Type::ObjCObjectPointer:
1972 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
1976 if (Queue.empty()) break;
1982 /// \brief Find the associated classes and namespaces for
1983 /// argument-dependent lookup for a call with the given set of
1986 /// This routine computes the sets of associated classes and associated
1987 /// namespaces searched by argument-dependent lookup
1988 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1990 Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1991 AssociatedNamespaceSet &AssociatedNamespaces,
1992 AssociatedClassSet &AssociatedClasses) {
1993 AssociatedNamespaces.clear();
1994 AssociatedClasses.clear();
1996 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1998 // C++ [basic.lookup.koenig]p2:
1999 // For each argument type T in the function call, there is a set
2000 // of zero or more associated namespaces and a set of zero or more
2001 // associated classes to be considered. The sets of namespaces and
2002 // classes is determined entirely by the types of the function
2003 // arguments (and the namespace of any template template
2005 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2006 Expr *Arg = Args[ArgIdx];
2008 if (Arg->getType() != Context.OverloadTy) {
2009 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2013 // [...] In addition, if the argument is the name or address of a
2014 // set of overloaded functions and/or function templates, its
2015 // associated classes and namespaces are the union of those
2016 // associated with each of the members of the set: the namespace
2017 // in which the function or function template is defined and the
2018 // classes and namespaces associated with its (non-dependent)
2019 // parameter types and return type.
2020 Arg = Arg->IgnoreParens();
2021 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2022 if (unaryOp->getOpcode() == UO_AddrOf)
2023 Arg = unaryOp->getSubExpr();
2025 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2028 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2030 // Look through any using declarations to find the underlying function.
2031 NamedDecl *Fn = (*I)->getUnderlyingDecl();
2033 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2035 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2037 // Add the classes and namespaces associated with the parameter
2038 // types and return type of this function.
2039 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2044 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2045 /// an acceptable non-member overloaded operator for a call whose
2046 /// arguments have types T1 (and, if non-empty, T2). This routine
2047 /// implements the check in C++ [over.match.oper]p3b2 concerning
2048 /// enumeration types.
2050 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2051 QualType T1, QualType T2,
2052 ASTContext &Context) {
2053 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2056 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2059 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2060 if (Proto->getNumArgs() < 1)
2063 if (T1->isEnumeralType()) {
2064 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2065 if (Context.hasSameUnqualifiedType(T1, ArgType))
2069 if (Proto->getNumArgs() < 2)
2072 if (!T2.isNull() && T2->isEnumeralType()) {
2073 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2074 if (Context.hasSameUnqualifiedType(T2, ArgType))
2081 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2083 LookupNameKind NameKind,
2084 RedeclarationKind Redecl) {
2085 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2087 return R.getAsSingle<NamedDecl>();
2090 /// \brief Find the protocol with the given name, if any.
2091 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2092 SourceLocation IdLoc) {
2093 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2094 LookupObjCProtocolName);
2095 return cast_or_null<ObjCProtocolDecl>(D);
2098 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2099 QualType T1, QualType T2,
2100 UnresolvedSetImpl &Functions) {
2101 // C++ [over.match.oper]p3:
2102 // -- The set of non-member candidates is the result of the
2103 // unqualified lookup of operator@ in the context of the
2104 // expression according to the usual rules for name lookup in
2105 // unqualified function calls (3.4.2) except that all member
2106 // functions are ignored. However, if no operand has a class
2107 // type, only those non-member functions in the lookup set
2108 // that have a first parameter of type T1 or "reference to
2109 // (possibly cv-qualified) T1", when T1 is an enumeration
2110 // type, or (if there is a right operand) a second parameter
2111 // of type T2 or "reference to (possibly cv-qualified) T2",
2112 // when T2 is an enumeration type, are candidate functions.
2113 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2114 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2115 LookupName(Operators, S);
2117 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2119 if (Operators.empty())
2122 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2123 Op != OpEnd; ++Op) {
2124 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2125 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2126 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2127 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2128 } else if (FunctionTemplateDecl *FunTmpl
2129 = dyn_cast<FunctionTemplateDecl>(Found)) {
2130 // FIXME: friend operators?
2131 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2133 if (!FunTmpl->getDeclContext()->isRecord())
2134 Functions.addDecl(*Op, Op.getAccess());
2139 /// \brief Look up the constructors for the given class.
2140 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2141 // If the copy constructor has not yet been declared, do so now.
2142 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2143 if (!Class->hasDeclaredDefaultConstructor())
2144 DeclareImplicitDefaultConstructor(Class);
2145 if (!Class->hasDeclaredCopyConstructor())
2146 DeclareImplicitCopyConstructor(Class);
2149 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2150 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2151 return Class->lookup(Name);
2154 /// \brief Look for the destructor of the given class.
2156 /// During semantic analysis, this routine should be used in lieu of
2157 /// CXXRecordDecl::getDestructor().
2159 /// \returns The destructor for this class.
2160 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2161 // If the destructor has not yet been declared, do so now.
2162 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2163 !Class->hasDeclaredDestructor())
2164 DeclareImplicitDestructor(Class);
2166 return Class->getDestructor();
2169 void ADLResult::insert(NamedDecl *New) {
2170 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2172 // If we haven't yet seen a decl for this key, or the last decl
2173 // was exactly this one, we're done.
2174 if (Old == 0 || Old == New) {
2179 // Otherwise, decide which is a more recent redeclaration.
2180 FunctionDecl *OldFD, *NewFD;
2181 if (isa<FunctionTemplateDecl>(New)) {
2182 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2183 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2185 OldFD = cast<FunctionDecl>(Old);
2186 NewFD = cast<FunctionDecl>(New);
2189 FunctionDecl *Cursor = NewFD;
2191 Cursor = Cursor->getPreviousDeclaration();
2193 // If we got to the end without finding OldFD, OldFD is the newer
2194 // declaration; leave things as they are.
2195 if (!Cursor) return;
2197 // If we do find OldFD, then NewFD is newer.
2198 if (Cursor == OldFD) break;
2200 // Otherwise, keep looking.
2206 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2207 Expr **Args, unsigned NumArgs,
2209 bool StdNamespaceIsAssociated) {
2210 // Find all of the associated namespaces and classes based on the
2211 // arguments we have.
2212 AssociatedNamespaceSet AssociatedNamespaces;
2213 AssociatedClassSet AssociatedClasses;
2214 FindAssociatedClassesAndNamespaces(Args, NumArgs,
2215 AssociatedNamespaces,
2217 if (StdNamespaceIsAssociated && StdNamespace)
2218 AssociatedNamespaces.insert(getStdNamespace());
2222 T1 = Args[0]->getType();
2224 T2 = Args[1]->getType();
2227 // C++ [basic.lookup.argdep]p3:
2228 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2229 // and let Y be the lookup set produced by argument dependent
2230 // lookup (defined as follows). If X contains [...] then Y is
2231 // empty. Otherwise Y is the set of declarations found in the
2232 // namespaces associated with the argument types as described
2233 // below. The set of declarations found by the lookup of the name
2234 // is the union of X and Y.
2236 // Here, we compute Y and add its members to the overloaded
2238 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2239 NSEnd = AssociatedNamespaces.end();
2240 NS != NSEnd; ++NS) {
2241 // When considering an associated namespace, the lookup is the
2242 // same as the lookup performed when the associated namespace is
2243 // used as a qualifier (3.4.3.2) except that:
2245 // -- Any using-directives in the associated namespace are
2248 // -- Any namespace-scope friend functions declared in
2249 // associated classes are visible within their respective
2250 // namespaces even if they are not visible during an ordinary
2252 DeclContext::lookup_iterator I, E;
2253 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
2255 // If the only declaration here is an ordinary friend, consider
2256 // it only if it was declared in an associated classes.
2257 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
2258 DeclContext *LexDC = D->getLexicalDeclContext();
2259 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2263 if (isa<UsingShadowDecl>(D))
2264 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2266 if (isa<FunctionDecl>(D)) {
2268 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2271 } else if (!isa<FunctionTemplateDecl>(D))
2279 //----------------------------------------------------------------------------
2280 // Search for all visible declarations.
2281 //----------------------------------------------------------------------------
2282 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2286 class ShadowContextRAII;
2288 class VisibleDeclsRecord {
2290 /// \brief An entry in the shadow map, which is optimized to store a
2291 /// single declaration (the common case) but can also store a list
2292 /// of declarations.
2293 class ShadowMapEntry {
2294 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2296 /// \brief Contains either the solitary NamedDecl * or a vector
2297 /// of declarations.
2298 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2301 ShadowMapEntry() : DeclOrVector() { }
2303 void Add(NamedDecl *ND);
2307 typedef NamedDecl * const *iterator;
2313 /// \brief A mapping from declaration names to the declarations that have
2314 /// this name within a particular scope.
2315 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2317 /// \brief A list of shadow maps, which is used to model name hiding.
2318 std::list<ShadowMap> ShadowMaps;
2320 /// \brief The declaration contexts we have already visited.
2321 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2323 friend class ShadowContextRAII;
2326 /// \brief Determine whether we have already visited this context
2327 /// (and, if not, note that we are going to visit that context now).
2328 bool visitedContext(DeclContext *Ctx) {
2329 return !VisitedContexts.insert(Ctx);
2332 bool alreadyVisitedContext(DeclContext *Ctx) {
2333 return VisitedContexts.count(Ctx);
2336 /// \brief Determine whether the given declaration is hidden in the
2339 /// \returns the declaration that hides the given declaration, or
2340 /// NULL if no such declaration exists.
2341 NamedDecl *checkHidden(NamedDecl *ND);
2343 /// \brief Add a declaration to the current shadow map.
2344 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2347 /// \brief RAII object that records when we've entered a shadow context.
2348 class ShadowContextRAII {
2349 VisibleDeclsRecord &Visible;
2351 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2354 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2355 Visible.ShadowMaps.push_back(ShadowMap());
2358 ~ShadowContextRAII() {
2359 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2360 EEnd = Visible.ShadowMaps.back().end();
2363 E->second.Destroy();
2365 Visible.ShadowMaps.pop_back();
2369 } // end anonymous namespace
2371 void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2372 if (DeclOrVector.isNull()) {
2373 // 0 - > 1 elements: just set the single element information.
2378 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2379 // 1 -> 2 elements: create the vector of results and push in the
2380 // existing declaration.
2381 DeclVector *Vec = new DeclVector;
2382 Vec->push_back(PrevND);
2386 // Add the new element to the end of the vector.
2387 DeclOrVector.get<DeclVector*>()->push_back(ND);
2390 void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2391 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2393 DeclOrVector = ((NamedDecl *)0);
2397 VisibleDeclsRecord::ShadowMapEntry::iterator
2398 VisibleDeclsRecord::ShadowMapEntry::begin() {
2399 if (DeclOrVector.isNull())
2402 if (DeclOrVector.is<NamedDecl *>())
2403 return DeclOrVector.getAddrOf<NamedDecl *>();
2405 return DeclOrVector.get<DeclVector *>()->begin();
2408 VisibleDeclsRecord::ShadowMapEntry::iterator
2409 VisibleDeclsRecord::ShadowMapEntry::end() {
2410 if (DeclOrVector.isNull())
2413 if (DeclOrVector.dyn_cast<NamedDecl *>())
2414 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2416 return DeclOrVector.get<DeclVector *>()->end();
2419 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2420 // Look through using declarations.
2421 ND = ND->getUnderlyingDecl();
2423 unsigned IDNS = ND->getIdentifierNamespace();
2424 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2425 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2426 SM != SMEnd; ++SM) {
2427 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2428 if (Pos == SM->end())
2431 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2432 IEnd = Pos->second.end();
2434 // A tag declaration does not hide a non-tag declaration.
2435 if ((*I)->hasTagIdentifierNamespace() &&
2436 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2437 Decl::IDNS_ObjCProtocol)))
2440 // Protocols are in distinct namespaces from everything else.
2441 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2442 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2443 (*I)->getIdentifierNamespace() != IDNS)
2446 // Functions and function templates in the same scope overload
2447 // rather than hide. FIXME: Look for hiding based on function
2449 if ((*I)->isFunctionOrFunctionTemplate() &&
2450 ND->isFunctionOrFunctionTemplate() &&
2451 SM == ShadowMaps.rbegin())
2454 // We've found a declaration that hides this one.
2462 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2463 bool QualifiedNameLookup,
2465 VisibleDeclConsumer &Consumer,
2466 VisibleDeclsRecord &Visited) {
2470 // Make sure we don't visit the same context twice.
2471 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2474 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2475 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2477 // Enumerate all of the results in this context.
2478 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2479 CurCtx = CurCtx->getNextContext()) {
2480 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2481 DEnd = CurCtx->decls_end();
2483 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
2484 if (Result.isAcceptableDecl(ND)) {
2485 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
2488 } else if (ObjCForwardProtocolDecl *ForwardProto
2489 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2490 for (ObjCForwardProtocolDecl::protocol_iterator
2491 P = ForwardProto->protocol_begin(),
2492 PEnd = ForwardProto->protocol_end();
2495 if (Result.isAcceptableDecl(*P)) {
2496 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2500 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2501 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2503 ObjCInterfaceDecl *IFace = I->getInterface();
2504 if (Result.isAcceptableDecl(IFace)) {
2505 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2511 // Visit transparent contexts and inline namespaces inside this context.
2512 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2513 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
2514 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
2520 // Traverse using directives for qualified name lookup.
2521 if (QualifiedNameLookup) {
2522 ShadowContextRAII Shadow(Visited);
2523 DeclContext::udir_iterator I, E;
2524 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2525 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
2526 QualifiedNameLookup, InBaseClass, Consumer, Visited);
2530 // Traverse the contexts of inherited C++ classes.
2531 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2532 if (!Record->hasDefinition())
2535 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2536 BEnd = Record->bases_end();
2538 QualType BaseType = B->getType();
2540 // Don't look into dependent bases, because name lookup can't look
2542 if (BaseType->isDependentType())
2545 const RecordType *Record = BaseType->getAs<RecordType>();
2549 // FIXME: It would be nice to be able to determine whether referencing
2550 // a particular member would be ambiguous. For example, given
2552 // struct A { int member; };
2553 // struct B { int member; };
2554 // struct C : A, B { };
2556 // void f(C *c) { c->### }
2558 // accessing 'member' would result in an ambiguity. However, we
2559 // could be smart enough to qualify the member with the base
2568 // Find results in this base class (and its bases).
2569 ShadowContextRAII Shadow(Visited);
2570 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2571 true, Consumer, Visited);
2575 // Traverse the contexts of Objective-C classes.
2576 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2577 // Traverse categories.
2578 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2579 Category; Category = Category->getNextClassCategory()) {
2580 ShadowContextRAII Shadow(Visited);
2581 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2585 // Traverse protocols.
2586 for (ObjCInterfaceDecl::all_protocol_iterator
2587 I = IFace->all_referenced_protocol_begin(),
2588 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
2589 ShadowContextRAII Shadow(Visited);
2590 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2594 // Traverse the superclass.
2595 if (IFace->getSuperClass()) {
2596 ShadowContextRAII Shadow(Visited);
2597 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
2598 true, Consumer, Visited);
2601 // If there is an implementation, traverse it. We do this to find
2602 // synthesized ivars.
2603 if (IFace->getImplementation()) {
2604 ShadowContextRAII Shadow(Visited);
2605 LookupVisibleDecls(IFace->getImplementation(), Result,
2606 QualifiedNameLookup, true, Consumer, Visited);
2608 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2609 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2610 E = Protocol->protocol_end(); I != E; ++I) {
2611 ShadowContextRAII Shadow(Visited);
2612 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2615 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2616 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2617 E = Category->protocol_end(); I != E; ++I) {
2618 ShadowContextRAII Shadow(Visited);
2619 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2623 // If there is an implementation, traverse it.
2624 if (Category->getImplementation()) {
2625 ShadowContextRAII Shadow(Visited);
2626 LookupVisibleDecls(Category->getImplementation(), Result,
2627 QualifiedNameLookup, true, Consumer, Visited);
2632 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2633 UnqualUsingDirectiveSet &UDirs,
2634 VisibleDeclConsumer &Consumer,
2635 VisibleDeclsRecord &Visited) {
2639 if (!S->getEntity() ||
2641 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
2642 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2643 // Walk through the declarations in this Scope.
2644 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2646 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2647 if (Result.isAcceptableDecl(ND)) {
2648 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
2654 // FIXME: C++ [temp.local]p8
2655 DeclContext *Entity = 0;
2656 if (S->getEntity()) {
2657 // Look into this scope's declaration context, along with any of its
2658 // parent lookup contexts (e.g., enclosing classes), up to the point
2659 // where we hit the context stored in the next outer scope.
2660 Entity = (DeclContext *)S->getEntity();
2661 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
2663 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
2664 Ctx = Ctx->getLookupParent()) {
2665 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2666 if (Method->isInstanceMethod()) {
2667 // For instance methods, look for ivars in the method's interface.
2668 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2669 Result.getNameLoc(), Sema::LookupMemberName);
2670 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
2671 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2672 /*InBaseClass=*/false, Consumer, Visited);
2674 // Look for properties from which we can synthesize ivars, if
2676 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2677 IFace->getImplementation() &&
2678 Result.getLookupKind() == Sema::LookupOrdinaryName) {
2679 for (ObjCInterfaceDecl::prop_iterator
2680 P = IFace->prop_begin(),
2681 PEnd = IFace->prop_end();
2683 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2684 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2685 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2693 // We've already performed all of the name lookup that we need
2694 // to for Objective-C methods; the next context will be the
2699 if (Ctx->isFunctionOrMethod())
2702 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
2703 /*InBaseClass=*/false, Consumer, Visited);
2705 } else if (!S->getParent()) {
2706 // Look into the translation unit scope. We walk through the translation
2707 // unit's declaration context, because the Scope itself won't have all of
2708 // the declarations if we loaded a precompiled header.
2709 // FIXME: We would like the translation unit's Scope object to point to the
2710 // translation unit, so we don't need this special "if" branch. However,
2711 // doing so would force the normal C++ name-lookup code to look into the
2712 // translation unit decl when the IdentifierInfo chains would suffice.
2713 // Once we fix that problem (which is part of a more general "don't look
2714 // in DeclContexts unless we have to" optimization), we can eliminate this.
2715 Entity = Result.getSema().Context.getTranslationUnitDecl();
2716 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
2717 /*InBaseClass=*/false, Consumer, Visited);
2721 // Lookup visible declarations in any namespaces found by using
2723 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2724 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2725 for (; UI != UEnd; ++UI)
2726 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
2727 Result, /*QualifiedNameLookup=*/false,
2728 /*InBaseClass=*/false, Consumer, Visited);
2731 // Lookup names in the parent scope.
2732 ShadowContextRAII Shadow(Visited);
2733 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2736 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2737 VisibleDeclConsumer &Consumer,
2738 bool IncludeGlobalScope) {
2739 // Determine the set of using directives available during
2740 // unqualified name lookup.
2742 UnqualUsingDirectiveSet UDirs;
2743 if (getLangOptions().CPlusPlus) {
2744 // Find the first namespace or translation-unit scope.
2745 while (S && !isNamespaceOrTranslationUnitScope(S))
2748 UDirs.visitScopeChain(Initial, S);
2752 // Look for visible declarations.
2753 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2754 VisibleDeclsRecord Visited;
2755 if (!IncludeGlobalScope)
2756 Visited.visitedContext(Context.getTranslationUnitDecl());
2757 ShadowContextRAII Shadow(Visited);
2758 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2761 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2762 VisibleDeclConsumer &Consumer,
2763 bool IncludeGlobalScope) {
2764 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2765 VisibleDeclsRecord Visited;
2766 if (!IncludeGlobalScope)
2767 Visited.visitedContext(Context.getTranslationUnitDecl());
2768 ShadowContextRAII Shadow(Visited);
2769 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2770 /*InBaseClass=*/false, Consumer, Visited);
2773 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
2774 /// If GnuLabelLoc is a valid source location, then this is a definition
2775 /// of an __label__ label name, otherwise it is a normal label definition
2777 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
2778 SourceLocation GnuLabelLoc) {
2779 // Do a lookup to see if we have a label with this name already.
2782 if (GnuLabelLoc.isValid()) {
2783 // Local label definitions always shadow existing labels.
2784 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
2785 Scope *S = CurScope;
2786 PushOnScopeChains(Res, S, true);
2787 return cast<LabelDecl>(Res);
2790 // Not a GNU local label.
2791 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
2792 // If we found a label, check to see if it is in the same context as us.
2793 // When in a Block, we don't want to reuse a label in an enclosing function.
2794 if (Res && Res->getDeclContext() != CurContext)
2797 // If not forward referenced or defined already, create the backing decl.
2798 Res = LabelDecl::Create(Context, CurContext, Loc, II);
2799 Scope *S = CurScope->getFnParent();
2800 assert(S && "Not in a function?");
2801 PushOnScopeChains(Res, S, true);
2803 return cast<LabelDecl>(Res);
2806 //===----------------------------------------------------------------------===//
2808 //===----------------------------------------------------------------------===//
2811 class TypoCorrectionConsumer : public VisibleDeclConsumer {
2812 /// \brief The name written that is a typo in the source.
2813 llvm::StringRef Typo;
2815 /// \brief The results found that have the smallest edit distance
2816 /// found (so far) with the typo name.
2818 /// The boolean value indicates whether there is a keyword with this name.
2819 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
2821 /// \brief The best edit distance found so far.
2822 unsigned BestEditDistance;
2825 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2826 : Typo(Typo->getName()),
2827 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
2829 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
2830 void FoundName(llvm::StringRef Name);
2831 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
2833 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2834 iterator begin() { return BestResults.begin(); }
2835 iterator end() { return BestResults.end(); }
2836 void erase(iterator I) { BestResults.erase(I); }
2837 unsigned size() const { return BestResults.size(); }
2838 bool empty() const { return BestResults.empty(); }
2840 bool &operator[](llvm::StringRef Name) {
2841 return BestResults[Name];
2844 unsigned getBestEditDistance() const { return BestEditDistance; }
2849 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2851 // Don't consider hidden names for typo correction.
2855 // Only consider entities with identifiers for names, ignoring
2856 // special names (constructors, overloaded operators, selectors,
2858 IdentifierInfo *Name = ND->getIdentifier();
2862 FoundName(Name->getName());
2865 void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
2866 // Use a simple length-based heuristic to determine the minimum possible
2867 // edit distance. If the minimum isn't good enough, bail out early.
2868 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2869 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2872 // Compute an upper bound on the allowable edit distance, so that the
2873 // edit-distance algorithm can short-circuit.
2874 unsigned UpperBound =
2875 std::min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
2877 // Compute the edit distance between the typo and the name of this
2878 // entity. If this edit distance is not worse than the best edit
2879 // distance we've seen so far, add it to the list of results.
2880 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
2884 if (ED < BestEditDistance) {
2885 // This result is better than any we've seen before; clear out
2886 // the previous results.
2887 BestResults.clear();
2888 BestEditDistance = ED;
2889 } else if (ED > BestEditDistance) {
2890 // This result is worse than the best results we've seen so far;
2895 // Add this name to the list of results. By not assigning a value, we
2896 // keep the current value if we've seen this name before (either as a
2897 // keyword or as a declaration), or get the default value (not a keyword)
2898 // if we haven't seen it before.
2899 (void)BestResults[Name];
2902 void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2903 llvm::StringRef Keyword) {
2904 // Compute the edit distance between the typo and this keyword.
2905 // If this edit distance is not worse than the best edit
2906 // distance we've seen so far, add it to the list of results.
2907 unsigned ED = Typo.edit_distance(Keyword);
2908 if (ED < BestEditDistance) {
2909 BestResults.clear();
2910 BestEditDistance = ED;
2911 } else if (ED > BestEditDistance) {
2912 // This result is worse than the best results we've seen so far;
2917 BestResults[Keyword] = true;
2920 /// \brief Perform name lookup for a possible result for typo correction.
2921 static void LookupPotentialTypoResult(Sema &SemaRef,
2923 IdentifierInfo *Name,
2924 Scope *S, CXXScopeSpec *SS,
2925 DeclContext *MemberContext,
2926 bool EnteringContext,
2927 Sema::CorrectTypoContext CTC) {
2928 Res.suppressDiagnostics();
2930 Res.setLookupName(Name);
2931 if (MemberContext) {
2932 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2933 if (CTC == Sema::CTC_ObjCIvarLookup) {
2934 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2941 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2948 SemaRef.LookupQualifiedName(Res, MemberContext);
2952 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2955 // Fake ivar lookup; this should really be part of
2956 // LookupParsedName.
2957 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2958 if (Method->isInstanceMethod() && Method->getClassInterface() &&
2960 (Res.isSingleResult() &&
2961 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
2962 if (ObjCIvarDecl *IV
2963 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2971 /// \brief Try to "correct" a typo in the source code by finding
2972 /// visible declarations whose names are similar to the name that was
2973 /// present in the source code.
2975 /// \param Res the \c LookupResult structure that contains the name
2976 /// that was present in the source code along with the name-lookup
2977 /// criteria used to search for the name. On success, this structure
2978 /// will contain the results of name lookup.
2980 /// \param S the scope in which name lookup occurs.
2982 /// \param SS the nested-name-specifier that precedes the name we're
2983 /// looking for, if present.
2985 /// \param MemberContext if non-NULL, the context in which to look for
2986 /// a member access expression.
2988 /// \param EnteringContext whether we're entering the context described by
2989 /// the nested-name-specifier SS.
2991 /// \param CTC The context in which typo correction occurs, which impacts the
2992 /// set of keywords permitted.
2994 /// \param OPT when non-NULL, the search for visible declarations will
2995 /// also walk the protocols in the qualified interfaces of \p OPT.
2997 /// \returns the corrected name if the typo was corrected, otherwise returns an
2998 /// empty \c DeclarationName. When a typo was corrected, the result structure
2999 /// may contain the results of name lookup for the correct name or it may be
3001 DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
3002 DeclContext *MemberContext,
3003 bool EnteringContext,
3004 CorrectTypoContext CTC,
3005 const ObjCObjectPointerType *OPT) {
3006 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
3007 return DeclarationName();
3009 // We only attempt to correct typos for identifiers.
3010 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
3012 return DeclarationName();
3014 // If the scope specifier itself was invalid, don't try to correct
3016 if (SS && SS->isInvalid())
3017 return DeclarationName();
3019 // Never try to correct typos during template deduction or
3021 if (!ActiveTemplateInstantiations.empty())
3022 return DeclarationName();
3024 TypoCorrectionConsumer Consumer(Typo);
3026 // Perform name lookup to find visible, similarly-named entities.
3027 bool IsUnqualifiedLookup = false;
3028 if (MemberContext) {
3029 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
3031 // Look in qualified interfaces.
3033 for (ObjCObjectPointerType::qual_iterator
3034 I = OPT->qual_begin(), E = OPT->qual_end();
3036 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
3038 } else if (SS && SS->isSet()) {
3039 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3041 return DeclarationName();
3043 // Provide a stop gap for files that are just seriously broken. Trying
3044 // to correct all typos can turn into a HUGE performance penalty, causing
3045 // some files to take minutes to get rejected by the parser.
3046 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3047 return DeclarationName();
3050 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
3052 IsUnqualifiedLookup = true;
3053 UnqualifiedTyposCorrectedMap::iterator Cached
3054 = UnqualifiedTyposCorrected.find(Typo);
3055 if (Cached == UnqualifiedTyposCorrected.end()) {
3056 // Provide a stop gap for files that are just seriously broken. Trying
3057 // to correct all typos can turn into a HUGE performance penalty, causing
3058 // some files to take minutes to get rejected by the parser.
3059 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3060 return DeclarationName();
3062 // For unqualified lookup, look through all of the names that we have
3063 // seen in this translation unit.
3064 for (IdentifierTable::iterator I = Context.Idents.begin(),
3065 IEnd = Context.Idents.end();
3067 Consumer.FoundName(I->getKey());
3069 // Walk through identifiers in external identifier sources.
3070 if (IdentifierInfoLookup *External
3071 = Context.Idents.getExternalIdentifierLookup()) {
3072 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
3074 llvm::StringRef Name = Iter->Next();
3078 Consumer.FoundName(Name);
3082 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3083 // end up adding the keyword below.
3084 if (Cached->second.first.empty())
3085 return DeclarationName();
3087 if (!Cached->second.second)
3088 Consumer.FoundName(Cached->second.first);
3092 // Add context-dependent keywords.
3093 bool WantTypeSpecifiers = false;
3094 bool WantExpressionKeywords = false;
3095 bool WantCXXNamedCasts = false;
3096 bool WantRemainingKeywords = false;
3099 WantTypeSpecifiers = true;
3100 WantExpressionKeywords = true;
3101 WantCXXNamedCasts = true;
3102 WantRemainingKeywords = true;
3104 if (ObjCMethodDecl *Method = getCurMethodDecl())
3105 if (Method->getClassInterface() &&
3106 Method->getClassInterface()->getSuperClass())
3107 Consumer.addKeywordResult(Context, "super");
3111 case CTC_NoKeywords:
3115 WantTypeSpecifiers = true;
3118 case CTC_ObjCMessageReceiver:
3119 Consumer.addKeywordResult(Context, "super");
3120 // Fall through to handle message receivers like expressions.
3122 case CTC_Expression:
3123 if (getLangOptions().CPlusPlus)
3124 WantTypeSpecifiers = true;
3125 WantExpressionKeywords = true;
3126 // Fall through to get C++ named casts.
3129 WantCXXNamedCasts = true;
3132 case CTC_ObjCPropertyLookup:
3133 // FIXME: Add "isa"?
3136 case CTC_MemberLookup:
3137 if (getLangOptions().CPlusPlus)
3138 Consumer.addKeywordResult(Context, "template");
3141 case CTC_ObjCIvarLookup:
3145 if (WantTypeSpecifiers) {
3146 // Add type-specifier keywords to the set of results.
3147 const char *CTypeSpecs[] = {
3148 "char", "const", "double", "enum", "float", "int", "long", "short",
3149 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3150 "_Complex", "_Imaginary",
3151 // storage-specifiers as well
3152 "extern", "inline", "static", "typedef"
3155 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3156 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3157 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
3159 if (getLangOptions().C99)
3160 Consumer.addKeywordResult(Context, "restrict");
3161 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3162 Consumer.addKeywordResult(Context, "bool");
3164 if (getLangOptions().CPlusPlus) {
3165 Consumer.addKeywordResult(Context, "class");
3166 Consumer.addKeywordResult(Context, "typename");
3167 Consumer.addKeywordResult(Context, "wchar_t");
3169 if (getLangOptions().CPlusPlus0x) {
3170 Consumer.addKeywordResult(Context, "char16_t");
3171 Consumer.addKeywordResult(Context, "char32_t");
3172 Consumer.addKeywordResult(Context, "constexpr");
3173 Consumer.addKeywordResult(Context, "decltype");
3174 Consumer.addKeywordResult(Context, "thread_local");
3178 if (getLangOptions().GNUMode)
3179 Consumer.addKeywordResult(Context, "typeof");
3182 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
3183 Consumer.addKeywordResult(Context, "const_cast");
3184 Consumer.addKeywordResult(Context, "dynamic_cast");
3185 Consumer.addKeywordResult(Context, "reinterpret_cast");
3186 Consumer.addKeywordResult(Context, "static_cast");
3189 if (WantExpressionKeywords) {
3190 Consumer.addKeywordResult(Context, "sizeof");
3191 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3192 Consumer.addKeywordResult(Context, "false");
3193 Consumer.addKeywordResult(Context, "true");
3196 if (getLangOptions().CPlusPlus) {
3197 const char *CXXExprs[] = {
3198 "delete", "new", "operator", "throw", "typeid"
3200 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3201 for (unsigned I = 0; I != NumCXXExprs; ++I)
3202 Consumer.addKeywordResult(Context, CXXExprs[I]);
3204 if (isa<CXXMethodDecl>(CurContext) &&
3205 cast<CXXMethodDecl>(CurContext)->isInstance())
3206 Consumer.addKeywordResult(Context, "this");
3208 if (getLangOptions().CPlusPlus0x) {
3209 Consumer.addKeywordResult(Context, "alignof");
3210 Consumer.addKeywordResult(Context, "nullptr");
3215 if (WantRemainingKeywords) {
3216 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3218 const char *CStmts[] = {
3219 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3220 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3221 for (unsigned I = 0; I != NumCStmts; ++I)
3222 Consumer.addKeywordResult(Context, CStmts[I]);
3224 if (getLangOptions().CPlusPlus) {
3225 Consumer.addKeywordResult(Context, "catch");
3226 Consumer.addKeywordResult(Context, "try");
3229 if (S && S->getBreakParent())
3230 Consumer.addKeywordResult(Context, "break");
3232 if (S && S->getContinueParent())
3233 Consumer.addKeywordResult(Context, "continue");
3235 if (!getCurFunction()->SwitchStack.empty()) {
3236 Consumer.addKeywordResult(Context, "case");
3237 Consumer.addKeywordResult(Context, "default");
3240 if (getLangOptions().CPlusPlus) {
3241 Consumer.addKeywordResult(Context, "namespace");
3242 Consumer.addKeywordResult(Context, "template");
3245 if (S && S->isClassScope()) {
3246 Consumer.addKeywordResult(Context, "explicit");
3247 Consumer.addKeywordResult(Context, "friend");
3248 Consumer.addKeywordResult(Context, "mutable");
3249 Consumer.addKeywordResult(Context, "private");
3250 Consumer.addKeywordResult(Context, "protected");
3251 Consumer.addKeywordResult(Context, "public");
3252 Consumer.addKeywordResult(Context, "virtual");
3256 if (getLangOptions().CPlusPlus) {
3257 Consumer.addKeywordResult(Context, "using");
3259 if (getLangOptions().CPlusPlus0x)
3260 Consumer.addKeywordResult(Context, "static_assert");
3264 // If we haven't found anything, we're done.
3265 if (Consumer.empty()) {
3266 // If this was an unqualified lookup, note that no correction was found.
3267 if (IsUnqualifiedLookup)
3268 (void)UnqualifiedTyposCorrected[Typo];
3270 return DeclarationName();
3273 // Make sure that the user typed at least 3 characters for each correction
3274 // made. Otherwise, we don't even both looking at the results.
3276 // We also suppress exact matches; those should be handled by a
3277 // different mechanism (e.g., one that introduces qualification in
3279 unsigned ED = Consumer.getBestEditDistance();
3280 if (ED > 0 && Typo->getName().size() / ED < 3) {
3281 // If this was an unqualified lookup, note that no correction was found.
3282 if (IsUnqualifiedLookup)
3283 (void)UnqualifiedTyposCorrected[Typo];
3285 return DeclarationName();
3288 // Weed out any names that could not be found by name lookup.
3289 bool LastLookupWasAccepted = false;
3290 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3291 IEnd = Consumer.end();
3292 I != IEnd; /* Increment in loop. */) {
3293 // Keywords are always found.
3299 // Perform name lookup on this name.
3300 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
3301 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3302 EnteringContext, CTC);
3304 switch (Res.getResultKind()) {
3305 case LookupResult::NotFound:
3306 case LookupResult::NotFoundInCurrentInstantiation:
3307 case LookupResult::Ambiguous:
3308 // We didn't find this name in our scope, or didn't like what we found;
3310 Res.suppressDiagnostics();
3312 TypoCorrectionConsumer::iterator Next = I;
3317 LastLookupWasAccepted = false;
3320 case LookupResult::Found:
3321 case LookupResult::FoundOverloaded:
3322 case LookupResult::FoundUnresolvedValue:
3324 LastLookupWasAccepted = true;
3328 if (Res.isAmbiguous()) {
3329 // We don't deal with ambiguities.
3330 Res.suppressDiagnostics();
3332 return DeclarationName();
3336 // If only a single name remains, return that result.
3337 if (Consumer.size() == 1) {
3338 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
3339 if (Consumer.begin()->second) {
3340 Res.suppressDiagnostics();
3343 // Don't correct to a keyword that's the same as the typo; the keyword
3344 // wasn't actually in scope.
3346 Res.setLookupName(Typo);
3347 return DeclarationName();
3350 } else if (!LastLookupWasAccepted) {
3351 // Perform name lookup on this name.
3352 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3353 EnteringContext, CTC);
3356 // Record the correction for unqualified lookup.
3357 if (IsUnqualifiedLookup)
3358 UnqualifiedTyposCorrected[Typo]
3359 = std::make_pair(Name->getName(), Consumer.begin()->second);
3361 return &Context.Idents.get(Consumer.begin()->getKey());
3363 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
3364 && Consumer["super"]) {
3365 // Prefix 'super' when we're completing in a message-receiver
3367 Res.suppressDiagnostics();
3370 // Don't correct to a keyword that's the same as the typo; the keyword
3371 // wasn't actually in scope.
3373 Res.setLookupName(Typo);
3374 return DeclarationName();
3377 // Record the correction for unqualified lookup.
3378 if (IsUnqualifiedLookup)
3379 UnqualifiedTyposCorrected[Typo]
3380 = std::make_pair("super", Consumer.begin()->second);
3382 return &Context.Idents.get("super");
3385 Res.suppressDiagnostics();
3386 Res.setLookupName(Typo);
3388 // Record the correction for unqualified lookup.
3389 if (IsUnqualifiedLookup)
3390 (void)UnqualifiedTyposCorrected[Typo];
3392 return DeclarationName();