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/Overload.h"
18 #include "clang/Sema/DeclSpec.h"
19 #include "clang/Sema/Scope.h"
20 #include "clang/Sema/ScopeInfo.h"
21 #include "clang/Sema/TemplateDeduction.h"
22 #include "clang/Sema/ExternalSemaSource.h"
23 #include "clang/Sema/TypoCorrection.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/CXXInheritance.h"
26 #include "clang/AST/Decl.h"
27 #include "clang/AST/DeclCXX.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclTemplate.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/StringMap.h"
38 #include "llvm/Support/ErrorHandling.h"
48 using namespace clang;
52 class UnqualUsingEntry {
53 const DeclContext *Nominated;
54 const DeclContext *CommonAncestor;
57 UnqualUsingEntry(const DeclContext *Nominated,
58 const DeclContext *CommonAncestor)
59 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
62 const DeclContext *getCommonAncestor() const {
63 return CommonAncestor;
66 const DeclContext *getNominatedNamespace() const {
70 // Sort by the pointer value of the common ancestor.
72 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
73 return L.getCommonAncestor() < R.getCommonAncestor();
76 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
77 return E.getCommonAncestor() < DC;
80 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
81 return DC < E.getCommonAncestor();
86 /// A collection of using directives, as used by C++ unqualified
88 class UnqualUsingDirectiveSet {
89 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
92 llvm::SmallPtrSet<DeclContext*, 8> visited;
95 UnqualUsingDirectiveSet() {}
97 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
98 // C++ [namespace.udir]p1:
99 // During unqualified name lookup, the names appear as if they
100 // were declared in the nearest enclosing namespace which contains
101 // both the using-directive and the nominated namespace.
102 DeclContext *InnermostFileDC
103 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
104 assert(InnermostFileDC && InnermostFileDC->isFileContext());
106 for (; S; S = S->getParent()) {
107 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
108 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC);
109 visit(Ctx, EffectiveDC);
111 Scope::udir_iterator I = S->using_directives_begin(),
112 End = S->using_directives_end();
114 for (; I != End; ++I)
115 visit(*I, InnermostFileDC);
120 // Visits a context and collect all of its using directives
121 // recursively. Treats all using directives as if they were
122 // declared in the context.
124 // A given context is only every visited once, so it is important
125 // that contexts be visited from the inside out in order to get
126 // the effective DCs right.
127 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
128 if (!visited.insert(DC))
131 addUsingDirectives(DC, EffectiveDC);
134 // Visits a using directive and collects all of its using
135 // directives recursively. Treats all using directives as if they
136 // were declared in the effective DC.
137 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
138 DeclContext *NS = UD->getNominatedNamespace();
139 if (!visited.insert(NS))
142 addUsingDirective(UD, EffectiveDC);
143 addUsingDirectives(NS, EffectiveDC);
146 // Adds all the using directives in a context (and those nominated
147 // by its using directives, transitively) as if they appeared in
148 // the given effective context.
149 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
150 llvm::SmallVector<DeclContext*,4> queue;
152 DeclContext::udir_iterator I, End;
153 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
154 UsingDirectiveDecl *UD = *I;
155 DeclContext *NS = UD->getNominatedNamespace();
156 if (visited.insert(NS)) {
157 addUsingDirective(UD, EffectiveDC);
170 // Add a using directive as if it had been declared in the given
171 // context. This helps implement C++ [namespace.udir]p3:
172 // The using-directive is transitive: if a scope contains a
173 // using-directive that nominates a second namespace that itself
174 // contains using-directives, the effect is as if the
175 // using-directives from the second namespace also appeared in
177 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
178 // Find the common ancestor between the effective context and
179 // the nominated namespace.
180 DeclContext *Common = UD->getNominatedNamespace();
181 while (!Common->Encloses(EffectiveDC))
182 Common = Common->getParent();
183 Common = Common->getPrimaryContext();
185 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
189 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
192 typedef ListTy::const_iterator const_iterator;
194 const_iterator begin() const { return list.begin(); }
195 const_iterator end() const { return list.end(); }
197 std::pair<const_iterator,const_iterator>
198 getNamespacesFor(DeclContext *DC) const {
199 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
200 UnqualUsingEntry::Comparator());
205 // Retrieve the set of identifier namespaces that correspond to a
206 // specific kind of name lookup.
207 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
209 bool Redeclaration) {
212 case Sema::LookupObjCImplicitSelfParam:
213 case Sema::LookupOrdinaryName:
214 case Sema::LookupRedeclarationWithLinkage:
215 IDNS = Decl::IDNS_Ordinary;
217 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
219 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
223 case Sema::LookupOperatorName:
224 // Operator lookup is its own crazy thing; it is not the same
225 // as (e.g.) looking up an operator name for redeclaration.
226 assert(!Redeclaration && "cannot do redeclaration operator lookup");
227 IDNS = Decl::IDNS_NonMemberOperator;
230 case Sema::LookupTagName:
232 IDNS = Decl::IDNS_Type;
234 // When looking for a redeclaration of a tag name, we add:
235 // 1) TagFriend to find undeclared friend decls
236 // 2) Namespace because they can't "overload" with tag decls.
237 // 3) Tag because it includes class templates, which can't
238 // "overload" with tag decls.
240 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
242 IDNS = Decl::IDNS_Tag;
245 case Sema::LookupLabel:
246 IDNS = Decl::IDNS_Label;
249 case Sema::LookupMemberName:
250 IDNS = Decl::IDNS_Member;
252 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
255 case Sema::LookupNestedNameSpecifierName:
256 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
259 case Sema::LookupNamespaceName:
260 IDNS = Decl::IDNS_Namespace;
263 case Sema::LookupUsingDeclName:
264 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
265 | Decl::IDNS_Member | Decl::IDNS_Using;
268 case Sema::LookupObjCProtocolName:
269 IDNS = Decl::IDNS_ObjCProtocol;
272 case Sema::LookupAnyName:
273 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
274 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
281 void LookupResult::configure() {
282 IDNS = getIDNS(LookupKind, SemaRef.getLangOptions().CPlusPlus,
283 isForRedeclaration());
285 // If we're looking for one of the allocation or deallocation
286 // operators, make sure that the implicitly-declared new and delete
287 // operators can be found.
288 if (!isForRedeclaration()) {
289 switch (NameInfo.getName().getCXXOverloadedOperator()) {
293 case OO_Array_Delete:
294 SemaRef.DeclareGlobalNewDelete();
303 void LookupResult::sanity() const {
304 assert(ResultKind != NotFound || Decls.size() == 0);
305 assert(ResultKind != Found || Decls.size() == 1);
306 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
307 (Decls.size() == 1 &&
308 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
309 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
310 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
311 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
312 Ambiguity == AmbiguousBaseSubobjectTypes)));
313 assert((Paths != NULL) == (ResultKind == Ambiguous &&
314 (Ambiguity == AmbiguousBaseSubobjectTypes ||
315 Ambiguity == AmbiguousBaseSubobjects)));
318 // Necessary because CXXBasePaths is not complete in Sema.h
319 void LookupResult::deletePaths(CXXBasePaths *Paths) {
323 /// Resolves the result kind of this lookup.
324 void LookupResult::resolveKind() {
325 unsigned N = Decls.size();
327 // Fast case: no possible ambiguity.
329 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
333 // If there's a single decl, we need to examine it to decide what
334 // kind of lookup this is.
336 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
337 if (isa<FunctionTemplateDecl>(D))
338 ResultKind = FoundOverloaded;
339 else if (isa<UnresolvedUsingValueDecl>(D))
340 ResultKind = FoundUnresolvedValue;
344 // Don't do any extra resolution if we've already resolved as ambiguous.
345 if (ResultKind == Ambiguous) return;
347 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
348 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
350 bool Ambiguous = false;
351 bool HasTag = false, HasFunction = false, HasNonFunction = false;
352 bool HasFunctionTemplate = false, HasUnresolved = false;
354 unsigned UniqueTagIndex = 0;
358 NamedDecl *D = Decls[I]->getUnderlyingDecl();
359 D = cast<NamedDecl>(D->getCanonicalDecl());
361 // Redeclarations of types via typedef can occur both within a scope
362 // and, through using declarations and directives, across scopes. There is
363 // no ambiguity if they all refer to the same type, so unique based on the
365 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
366 if (!TD->getDeclContext()->isRecord()) {
367 QualType T = SemaRef.Context.getTypeDeclType(TD);
368 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
369 // The type is not unique; pull something off the back and continue
371 Decls[I] = Decls[--N];
377 if (!Unique.insert(D)) {
378 // If it's not unique, pull something off the back (and
379 // continue at this index).
380 Decls[I] = Decls[--N];
384 // Otherwise, do some decl type analysis and then continue.
386 if (isa<UnresolvedUsingValueDecl>(D)) {
387 HasUnresolved = true;
388 } else if (isa<TagDecl>(D)) {
393 } else if (isa<FunctionTemplateDecl>(D)) {
395 HasFunctionTemplate = true;
396 } else if (isa<FunctionDecl>(D)) {
401 HasNonFunction = true;
406 // C++ [basic.scope.hiding]p2:
407 // A class name or enumeration name can be hidden by the name of
408 // an object, function, or enumerator declared in the same
409 // scope. If a class or enumeration name and an object, function,
410 // or enumerator are declared in the same scope (in any order)
411 // with the same name, the class or enumeration name is hidden
412 // wherever the object, function, or enumerator name is visible.
413 // But it's still an error if there are distinct tag types found,
414 // even if they're not visible. (ref?)
415 if (HideTags && HasTag && !Ambiguous &&
416 (HasFunction || HasNonFunction || HasUnresolved)) {
417 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
418 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
419 Decls[UniqueTagIndex] = Decls[--N];
426 if (HasNonFunction && (HasFunction || HasUnresolved))
430 setAmbiguous(LookupResult::AmbiguousReference);
431 else if (HasUnresolved)
432 ResultKind = LookupResult::FoundUnresolvedValue;
433 else if (N > 1 || HasFunctionTemplate)
434 ResultKind = LookupResult::FoundOverloaded;
436 ResultKind = LookupResult::Found;
439 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
440 CXXBasePaths::const_paths_iterator I, E;
441 DeclContext::lookup_iterator DI, DE;
442 for (I = P.begin(), E = P.end(); I != E; ++I)
443 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
447 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
448 Paths = new CXXBasePaths;
450 addDeclsFromBasePaths(*Paths);
452 setAmbiguous(AmbiguousBaseSubobjects);
455 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
456 Paths = new CXXBasePaths;
458 addDeclsFromBasePaths(*Paths);
460 setAmbiguous(AmbiguousBaseSubobjectTypes);
463 void LookupResult::print(llvm::raw_ostream &Out) {
464 Out << Decls.size() << " result(s)";
465 if (isAmbiguous()) Out << ", ambiguous";
466 if (Paths) Out << ", base paths present";
468 for (iterator I = begin(), E = end(); I != E; ++I) {
474 /// \brief Lookup a builtin function, when name lookup would otherwise
476 static bool LookupBuiltin(Sema &S, LookupResult &R) {
477 Sema::LookupNameKind NameKind = R.getLookupKind();
479 // If we didn't find a use of this identifier, and if the identifier
480 // corresponds to a compiler builtin, create the decl object for the builtin
481 // now, injecting it into translation unit scope, and return it.
482 if (NameKind == Sema::LookupOrdinaryName ||
483 NameKind == Sema::LookupRedeclarationWithLinkage) {
484 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
486 // If this is a builtin on this (or all) targets, create the decl.
487 if (unsigned BuiltinID = II->getBuiltinID()) {
488 // In C++, we don't have any predefined library functions like
489 // 'malloc'. Instead, we'll just error.
490 if (S.getLangOptions().CPlusPlus &&
491 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
494 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
495 BuiltinID, S.TUScope,
496 R.isForRedeclaration(),
502 if (R.isForRedeclaration()) {
503 // If we're redeclaring this function anyway, forget that
504 // this was a builtin at all.
505 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
516 /// \brief Determine whether we can declare a special member function within
517 /// the class at this point.
518 static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
519 const CXXRecordDecl *Class) {
520 // Don't do it if the class is invalid.
521 if (Class->isInvalidDecl())
524 // We need to have a definition for the class.
525 if (!Class->getDefinition() || Class->isDependentContext())
528 // We can't be in the middle of defining the class.
529 if (const RecordType *RecordTy
530 = Context.getTypeDeclType(Class)->getAs<RecordType>())
531 return !RecordTy->isBeingDefined();
536 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
537 if (!CanDeclareSpecialMemberFunction(Context, Class))
540 // If the default constructor has not yet been declared, do so now.
541 if (Class->needsImplicitDefaultConstructor())
542 DeclareImplicitDefaultConstructor(Class);
544 // If the copy constructor has not yet been declared, do so now.
545 if (!Class->hasDeclaredCopyConstructor())
546 DeclareImplicitCopyConstructor(Class);
548 // If the copy assignment operator has not yet been declared, do so now.
549 if (!Class->hasDeclaredCopyAssignment())
550 DeclareImplicitCopyAssignment(Class);
552 // If the destructor has not yet been declared, do so now.
553 if (!Class->hasDeclaredDestructor())
554 DeclareImplicitDestructor(Class);
557 /// \brief Determine whether this is the name of an implicitly-declared
558 /// special member function.
559 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
560 switch (Name.getNameKind()) {
561 case DeclarationName::CXXConstructorName:
562 case DeclarationName::CXXDestructorName:
565 case DeclarationName::CXXOperatorName:
566 return Name.getCXXOverloadedOperator() == OO_Equal;
575 /// \brief If there are any implicit member functions with the given name
576 /// that need to be declared in the given declaration context, do so.
577 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
578 DeclarationName Name,
579 const DeclContext *DC) {
583 switch (Name.getNameKind()) {
584 case DeclarationName::CXXConstructorName:
585 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
586 if (Record->getDefinition() &&
587 CanDeclareSpecialMemberFunction(S.Context, Record)) {
588 if (Record->needsImplicitDefaultConstructor())
589 S.DeclareImplicitDefaultConstructor(
590 const_cast<CXXRecordDecl *>(Record));
591 if (!Record->hasDeclaredCopyConstructor())
592 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
596 case DeclarationName::CXXDestructorName:
597 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
598 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
599 CanDeclareSpecialMemberFunction(S.Context, Record))
600 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
603 case DeclarationName::CXXOperatorName:
604 if (Name.getCXXOverloadedOperator() != OO_Equal)
607 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
608 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
609 CanDeclareSpecialMemberFunction(S.Context, Record))
610 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
618 // Adds all qualifying matches for a name within a decl context to the
619 // given lookup result. Returns true if any matches were found.
620 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
623 // Lazily declare C++ special member functions.
624 if (S.getLangOptions().CPlusPlus)
625 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
627 // Perform lookup into this declaration context.
628 DeclContext::lookup_const_iterator I, E;
629 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
631 if (R.isAcceptableDecl(D)) {
637 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
640 if (R.getLookupName().getNameKind()
641 != DeclarationName::CXXConversionFunctionName ||
642 R.getLookupName().getCXXNameType()->isDependentType() ||
643 !isa<CXXRecordDecl>(DC))
647 // A specialization of a conversion function template is not found by
648 // name lookup. Instead, any conversion function templates visible in the
649 // context of the use are considered. [...]
650 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
651 if (!Record->isDefinition())
654 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
655 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
656 UEnd = Unresolved->end(); U != UEnd; ++U) {
657 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
661 // When we're performing lookup for the purposes of redeclaration, just
662 // add the conversion function template. When we deduce template
663 // arguments for specializations, we'll end up unifying the return
664 // type of the new declaration with the type of the function template.
665 if (R.isForRedeclaration()) {
666 R.addDecl(ConvTemplate);
672 // [...] For each such operator, if argument deduction succeeds
673 // (14.9.2.3), the resulting specialization is used as if found by
676 // When referencing a conversion function for any purpose other than
677 // a redeclaration (such that we'll be building an expression with the
678 // result), perform template argument deduction and place the
679 // specialization into the result set. We do this to avoid forcing all
680 // callers to perform special deduction for conversion functions.
681 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
682 FunctionDecl *Specialization = 0;
684 const FunctionProtoType *ConvProto
685 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
686 assert(ConvProto && "Nonsensical conversion function template type");
688 // Compute the type of the function that we would expect the conversion
689 // function to have, if it were to match the name given.
690 // FIXME: Calling convention!
691 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
692 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
693 EPI.ExceptionSpecType = EST_None;
694 EPI.NumExceptions = 0;
695 QualType ExpectedType
696 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
699 // Perform template argument deduction against the type that we would
700 // expect the function to have.
701 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
702 Specialization, Info)
703 == Sema::TDK_Success) {
704 R.addDecl(Specialization);
712 // Performs C++ unqualified lookup into the given file context.
714 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
715 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
717 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
719 // Perform direct name lookup into the LookupCtx.
720 bool Found = LookupDirect(S, R, NS);
722 // Perform direct name lookup into the namespaces nominated by the
723 // using directives whose common ancestor is this namespace.
724 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
725 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
727 for (; UI != UEnd; ++UI)
728 if (LookupDirect(S, R, UI->getNominatedNamespace()))
736 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
737 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
738 return Ctx->isFileContext();
742 // Find the next outer declaration context from this scope. This
743 // routine actually returns the semantic outer context, which may
744 // differ from the lexical context (encoded directly in the Scope
745 // stack) when we are parsing a member of a class template. In this
746 // case, the second element of the pair will be true, to indicate that
747 // name lookup should continue searching in this semantic context when
748 // it leaves the current template parameter scope.
749 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
750 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
751 DeclContext *Lexical = 0;
752 for (Scope *OuterS = S->getParent(); OuterS;
753 OuterS = OuterS->getParent()) {
754 if (OuterS->getEntity()) {
755 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
760 // C++ [temp.local]p8:
761 // In the definition of a member of a class template that appears
762 // outside of the namespace containing the class template
763 // definition, the name of a template-parameter hides the name of
764 // a member of this namespace.
771 // template<class T> class B {
776 // template<class C> void N::B<C>::f(C) {
777 // C b; // C is the template parameter, not N::C
780 // In this example, the lexical context we return is the
781 // TranslationUnit, while the semantic context is the namespace N.
782 if (!Lexical || !DC || !S->getParent() ||
783 !S->getParent()->isTemplateParamScope())
784 return std::make_pair(Lexical, false);
786 // Find the outermost template parameter scope.
787 // For the example, this is the scope for the template parameters of
788 // template<class C>.
789 Scope *OutermostTemplateScope = S->getParent();
790 while (OutermostTemplateScope->getParent() &&
791 OutermostTemplateScope->getParent()->isTemplateParamScope())
792 OutermostTemplateScope = OutermostTemplateScope->getParent();
794 // Find the namespace context in which the original scope occurs. In
795 // the example, this is namespace N.
796 DeclContext *Semantic = DC;
797 while (!Semantic->isFileContext())
798 Semantic = Semantic->getParent();
800 // Find the declaration context just outside of the template
801 // parameter scope. This is the context in which the template is
802 // being lexically declaration (a namespace context). In the
803 // example, this is the global scope.
804 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
805 Lexical->Encloses(Semantic))
806 return std::make_pair(Semantic, true);
808 return std::make_pair(Lexical, false);
811 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
812 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
814 DeclarationName Name = R.getLookupName();
816 // If this is the name of an implicitly-declared special member function,
817 // go through the scope stack to implicitly declare
818 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
819 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
820 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
821 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
824 // Implicitly declare member functions with the name we're looking for, if in
825 // fact we are in a scope where it matters.
828 IdentifierResolver::iterator
829 I = IdResolver.begin(Name),
830 IEnd = IdResolver.end();
832 // First we lookup local scope.
833 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
834 // ...During unqualified name lookup (3.4.1), the names appear as if
835 // they were declared in the nearest enclosing namespace which contains
836 // both the using-directive and the nominated namespace.
837 // [Note: in this context, "contains" means "contains directly or
841 // namespace A { int i; }
845 // using namespace A;
846 // ++i; // finds local 'i', A::i appears at global scope
850 DeclContext *OutsideOfTemplateParamDC = 0;
851 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
852 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
854 // Check whether the IdResolver has anything in this scope.
856 for (; I != IEnd && S->isDeclScope(*I); ++I) {
857 if (R.isAcceptableDecl(*I)) {
864 if (S->isClassScope())
865 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
866 R.setNamingClass(Record);
870 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
871 S->getParent() && !S->getParent()->isTemplateParamScope()) {
872 // We've just searched the last template parameter scope and
873 // found nothing, so look into the the contexts between the
874 // lexical and semantic declaration contexts returned by
875 // findOuterContext(). This implements the name lookup behavior
876 // of C++ [temp.local]p8.
877 Ctx = OutsideOfTemplateParamDC;
878 OutsideOfTemplateParamDC = 0;
882 DeclContext *OuterCtx;
883 bool SearchAfterTemplateScope;
884 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
885 if (SearchAfterTemplateScope)
886 OutsideOfTemplateParamDC = OuterCtx;
888 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
889 // We do not directly look into transparent contexts, since
890 // those entities will be found in the nearest enclosing
891 // non-transparent context.
892 if (Ctx->isTransparentContext())
895 // We do not look directly into function or method contexts,
896 // since all of the local variables and parameters of the
897 // function/method are present within the Scope.
898 if (Ctx->isFunctionOrMethod()) {
899 // If we have an Objective-C instance method, look for ivars
900 // in the corresponding interface.
901 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
902 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
903 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
904 ObjCInterfaceDecl *ClassDeclared;
905 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
906 Name.getAsIdentifierInfo(),
908 if (R.isAcceptableDecl(Ivar)) {
920 // Perform qualified name lookup into this context.
921 // FIXME: In some cases, we know that every name that could be found by
922 // this qualified name lookup will also be on the identifier chain. For
923 // example, inside a class without any base classes, we never need to
924 // perform qualified lookup because all of the members are on top of the
926 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
932 // Stop if we ran out of scopes.
933 // FIXME: This really, really shouldn't be happening.
934 if (!S) return false;
936 // If we are looking for members, no need to look into global/namespace scope.
937 if (R.getLookupKind() == LookupMemberName)
940 // Collect UsingDirectiveDecls in all scopes, and recursively all
941 // nominated namespaces by those using-directives.
943 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
944 // don't build it for each lookup!
946 UnqualUsingDirectiveSet UDirs;
947 UDirs.visitScopeChain(Initial, S);
950 // Lookup namespace scope, and global scope.
951 // Unqualified name lookup in C++ requires looking into scopes
952 // that aren't strictly lexical, and therefore we walk through the
953 // context as well as walking through the scopes.
955 for (; S; S = S->getParent()) {
956 // Check whether the IdResolver has anything in this scope.
958 for (; I != IEnd && S->isDeclScope(*I); ++I) {
959 if (R.isAcceptableDecl(*I)) {
960 // We found something. Look for anything else in our scope
961 // with this same name and in an acceptable identifier
962 // namespace, so that we can construct an overload set if we
969 if (Found && S->isTemplateParamScope()) {
974 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
975 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
976 S->getParent() && !S->getParent()->isTemplateParamScope()) {
977 // We've just searched the last template parameter scope and
978 // found nothing, so look into the the contexts between the
979 // lexical and semantic declaration contexts returned by
980 // findOuterContext(). This implements the name lookup behavior
981 // of C++ [temp.local]p8.
982 Ctx = OutsideOfTemplateParamDC;
983 OutsideOfTemplateParamDC = 0;
987 DeclContext *OuterCtx;
988 bool SearchAfterTemplateScope;
989 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
990 if (SearchAfterTemplateScope)
991 OutsideOfTemplateParamDC = OuterCtx;
993 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
994 // We do not directly look into transparent contexts, since
995 // those entities will be found in the nearest enclosing
996 // non-transparent context.
997 if (Ctx->isTransparentContext())
1000 // If we have a context, and it's not a context stashed in the
1001 // template parameter scope for an out-of-line definition, also
1002 // look into that context.
1003 if (!(Found && S && S->isTemplateParamScope())) {
1004 assert(Ctx->isFileContext() &&
1005 "We should have been looking only at file context here already.");
1007 // Look into context considering using-directives.
1008 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1017 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1022 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1029 /// @brief Perform unqualified name lookup starting from a given
1032 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1033 /// used to find names within the current scope. For example, 'x' in
1037 /// return x; // unqualified name look finds 'x' in the global scope
1041 /// Different lookup criteria can find different names. For example, a
1042 /// particular scope can have both a struct and a function of the same
1043 /// name, and each can be found by certain lookup criteria. For more
1044 /// information about lookup criteria, see the documentation for the
1045 /// class LookupCriteria.
1047 /// @param S The scope from which unqualified name lookup will
1048 /// begin. If the lookup criteria permits, name lookup may also search
1049 /// in the parent scopes.
1051 /// @param Name The name of the entity that we are searching for.
1053 /// @param Loc If provided, the source location where we're performing
1054 /// name lookup. At present, this is only used to produce diagnostics when
1055 /// C library functions (like "malloc") are implicitly declared.
1057 /// @returns The result of name lookup, which includes zero or more
1058 /// declarations and possibly additional information used to diagnose
1060 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1061 DeclarationName Name = R.getLookupName();
1062 if (!Name) return false;
1064 LookupNameKind NameKind = R.getLookupKind();
1066 if (!getLangOptions().CPlusPlus) {
1067 // Unqualified name lookup in C/Objective-C is purely lexical, so
1068 // search in the declarations attached to the name.
1069 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1070 // Find the nearest non-transparent declaration scope.
1071 while (!(S->getFlags() & Scope::DeclScope) ||
1073 static_cast<DeclContext *>(S->getEntity())
1074 ->isTransparentContext()))
1078 unsigned IDNS = R.getIdentifierNamespace();
1080 // Scan up the scope chain looking for a decl that matches this
1081 // identifier that is in the appropriate namespace. This search
1082 // should not take long, as shadowing of names is uncommon, and
1083 // deep shadowing is extremely uncommon.
1084 bool LeftStartingScope = false;
1086 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1087 IEnd = IdResolver.end();
1089 if ((*I)->isInIdentifierNamespace(IDNS)) {
1090 if (NameKind == LookupRedeclarationWithLinkage) {
1091 // Determine whether this (or a previous) declaration is
1093 if (!LeftStartingScope && !S->isDeclScope(*I))
1094 LeftStartingScope = true;
1096 // If we found something outside of our starting scope that
1097 // does not have linkage, skip it.
1098 if (LeftStartingScope && !((*I)->hasLinkage()))
1101 else if (NameKind == LookupObjCImplicitSelfParam &&
1102 !isa<ImplicitParamDecl>(*I))
1107 if ((*I)->getAttr<OverloadableAttr>()) {
1108 // If this declaration has the "overloadable" attribute, we
1109 // might have a set of overloaded functions.
1111 // Figure out what scope the identifier is in.
1112 while (!(S->getFlags() & Scope::DeclScope) ||
1113 !S->isDeclScope(*I))
1116 // Find the last declaration in this scope (with the same
1117 // name, naturally).
1118 IdentifierResolver::iterator LastI = I;
1119 for (++LastI; LastI != IEnd; ++LastI) {
1120 if (!S->isDeclScope(*LastI))
1131 // Perform C++ unqualified name lookup.
1132 if (CppLookupName(R, S))
1136 // If we didn't find a use of this identifier, and if the identifier
1137 // corresponds to a compiler builtin, create the decl object for the builtin
1138 // now, injecting it into translation unit scope, and return it.
1139 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1142 // If we didn't find a use of this identifier, the ExternalSource
1143 // may be able to handle the situation.
1144 // Note: some lookup failures are expected!
1145 // See e.g. R.isForRedeclaration().
1146 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1149 /// @brief Perform qualified name lookup in the namespaces nominated by
1150 /// using directives by the given context.
1152 /// C++98 [namespace.qual]p2:
1153 /// Given X::m (where X is a user-declared namespace), or given ::m
1154 /// (where X is the global namespace), let S be the set of all
1155 /// declarations of m in X and in the transitive closure of all
1156 /// namespaces nominated by using-directives in X and its used
1157 /// namespaces, except that using-directives are ignored in any
1158 /// namespace, including X, directly containing one or more
1159 /// declarations of m. No namespace is searched more than once in
1160 /// the lookup of a name. If S is the empty set, the program is
1161 /// ill-formed. Otherwise, if S has exactly one member, or if the
1162 /// context of the reference is a using-declaration
1163 /// (namespace.udecl), S is the required set of declarations of
1164 /// m. Otherwise if the use of m is not one that allows a unique
1165 /// declaration to be chosen from S, the program is ill-formed.
1166 /// C++98 [namespace.qual]p5:
1167 /// During the lookup of a qualified namespace member name, if the
1168 /// lookup finds more than one declaration of the member, and if one
1169 /// declaration introduces a class name or enumeration name and the
1170 /// other declarations either introduce the same object, the same
1171 /// enumerator or a set of functions, the non-type name hides the
1172 /// class or enumeration name if and only if the declarations are
1173 /// from the same namespace; otherwise (the declarations are from
1174 /// different namespaces), the program is ill-formed.
1175 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1176 DeclContext *StartDC) {
1177 assert(StartDC->isFileContext() && "start context is not a file context");
1179 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1180 DeclContext::udir_iterator E = StartDC->using_directives_end();
1182 if (I == E) return false;
1184 // We have at least added all these contexts to the queue.
1185 llvm::DenseSet<DeclContext*> Visited;
1186 Visited.insert(StartDC);
1188 // We have not yet looked into these namespaces, much less added
1189 // their "using-children" to the queue.
1190 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1192 // We have already looked into the initial namespace; seed the queue
1193 // with its using-children.
1194 for (; I != E; ++I) {
1195 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1196 if (Visited.insert(ND).second)
1197 Queue.push_back(ND);
1200 // The easiest way to implement the restriction in [namespace.qual]p5
1201 // is to check whether any of the individual results found a tag
1202 // and, if so, to declare an ambiguity if the final result is not
1204 bool FoundTag = false;
1205 bool FoundNonTag = false;
1207 LookupResult LocalR(LookupResult::Temporary, R);
1210 while (!Queue.empty()) {
1211 NamespaceDecl *ND = Queue.back();
1214 // We go through some convolutions here to avoid copying results
1215 // between LookupResults.
1216 bool UseLocal = !R.empty();
1217 LookupResult &DirectR = UseLocal ? LocalR : R;
1218 bool FoundDirect = LookupDirect(S, DirectR, ND);
1221 // First do any local hiding.
1222 DirectR.resolveKind();
1224 // If the local result is a tag, remember that.
1225 if (DirectR.isSingleTagDecl())
1230 // Append the local results to the total results if necessary.
1232 R.addAllDecls(LocalR);
1237 // If we find names in this namespace, ignore its using directives.
1243 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1244 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1245 if (Visited.insert(Nom).second)
1246 Queue.push_back(Nom);
1251 if (FoundTag && FoundNonTag)
1252 R.setAmbiguousQualifiedTagHiding();
1260 /// \brief Callback that looks for any member of a class with the given name.
1261 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1264 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1266 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1267 Path.Decls = BaseRecord->lookup(N);
1268 return Path.Decls.first != Path.Decls.second;
1271 /// \brief Determine whether the given set of member declarations contains only
1272 /// static members, nested types, and enumerators.
1273 template<typename InputIterator>
1274 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1275 Decl *D = (*First)->getUnderlyingDecl();
1276 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1279 if (isa<CXXMethodDecl>(D)) {
1280 // Determine whether all of the methods are static.
1281 bool AllMethodsAreStatic = true;
1282 for(; First != Last; ++First) {
1283 D = (*First)->getUnderlyingDecl();
1285 if (!isa<CXXMethodDecl>(D)) {
1286 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1290 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1291 AllMethodsAreStatic = false;
1296 if (AllMethodsAreStatic)
1303 /// \brief Perform qualified name lookup into a given context.
1305 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1306 /// names when the context of those names is explicit specified, e.g.,
1307 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1309 /// Different lookup criteria can find different names. For example, a
1310 /// particular scope can have both a struct and a function of the same
1311 /// name, and each can be found by certain lookup criteria. For more
1312 /// information about lookup criteria, see the documentation for the
1313 /// class LookupCriteria.
1315 /// \param R captures both the lookup criteria and any lookup results found.
1317 /// \param LookupCtx The context in which qualified name lookup will
1318 /// search. If the lookup criteria permits, name lookup may also search
1319 /// in the parent contexts or (for C++ classes) base classes.
1321 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1322 /// occurs as part of unqualified name lookup.
1324 /// \returns true if lookup succeeded, false if it failed.
1325 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1326 bool InUnqualifiedLookup) {
1327 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1329 if (!R.getLookupName())
1332 // Make sure that the declaration context is complete.
1333 assert((!isa<TagDecl>(LookupCtx) ||
1334 LookupCtx->isDependentContext() ||
1335 cast<TagDecl>(LookupCtx)->isDefinition() ||
1336 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1337 ->isBeingDefined()) &&
1338 "Declaration context must already be complete!");
1340 // Perform qualified name lookup into the LookupCtx.
1341 if (LookupDirect(*this, R, LookupCtx)) {
1343 if (isa<CXXRecordDecl>(LookupCtx))
1344 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1348 // Don't descend into implied contexts for redeclarations.
1349 // C++98 [namespace.qual]p6:
1350 // In a declaration for a namespace member in which the
1351 // declarator-id is a qualified-id, given that the qualified-id
1352 // for the namespace member has the form
1353 // nested-name-specifier unqualified-id
1354 // the unqualified-id shall name a member of the namespace
1355 // designated by the nested-name-specifier.
1356 // See also [class.mfct]p5 and [class.static.data]p2.
1357 if (R.isForRedeclaration())
1360 // If this is a namespace, look it up in the implied namespaces.
1361 if (LookupCtx->isFileContext())
1362 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1364 // If this isn't a C++ class, we aren't allowed to look into base
1365 // classes, we're done.
1366 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1367 if (!LookupRec || !LookupRec->getDefinition())
1370 // If we're performing qualified name lookup into a dependent class,
1371 // then we are actually looking into a current instantiation. If we have any
1372 // dependent base classes, then we either have to delay lookup until
1373 // template instantiation time (at which point all bases will be available)
1374 // or we have to fail.
1375 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1376 LookupRec->hasAnyDependentBases()) {
1377 R.setNotFoundInCurrentInstantiation();
1381 // Perform lookup into our base classes.
1383 Paths.setOrigin(LookupRec);
1385 // Look for this member in our base classes
1386 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1387 switch (R.getLookupKind()) {
1388 case LookupObjCImplicitSelfParam:
1389 case LookupOrdinaryName:
1390 case LookupMemberName:
1391 case LookupRedeclarationWithLinkage:
1392 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1396 BaseCallback = &CXXRecordDecl::FindTagMember;
1400 BaseCallback = &LookupAnyMember;
1403 case LookupUsingDeclName:
1404 // This lookup is for redeclarations only.
1406 case LookupOperatorName:
1407 case LookupNamespaceName:
1408 case LookupObjCProtocolName:
1410 // These lookups will never find a member in a C++ class (or base class).
1413 case LookupNestedNameSpecifierName:
1414 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1418 if (!LookupRec->lookupInBases(BaseCallback,
1419 R.getLookupName().getAsOpaquePtr(), Paths))
1422 R.setNamingClass(LookupRec);
1424 // C++ [class.member.lookup]p2:
1425 // [...] If the resulting set of declarations are not all from
1426 // sub-objects of the same type, or the set has a nonstatic member
1427 // and includes members from distinct sub-objects, there is an
1428 // ambiguity and the program is ill-formed. Otherwise that set is
1429 // the result of the lookup.
1430 QualType SubobjectType;
1431 int SubobjectNumber = 0;
1432 AccessSpecifier SubobjectAccess = AS_none;
1434 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1435 Path != PathEnd; ++Path) {
1436 const CXXBasePathElement &PathElement = Path->back();
1438 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1439 // across all paths.
1440 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1442 // Determine whether we're looking at a distinct sub-object or not.
1443 if (SubobjectType.isNull()) {
1444 // This is the first subobject we've looked at. Record its type.
1445 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1446 SubobjectNumber = PathElement.SubobjectNumber;
1451 != Context.getCanonicalType(PathElement.Base->getType())) {
1452 // We found members of the given name in two subobjects of
1453 // different types. If the declaration sets aren't the same, this
1454 // this lookup is ambiguous.
1455 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1456 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1457 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1458 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1460 while (FirstD != FirstPath->Decls.second &&
1461 CurrentD != Path->Decls.second) {
1462 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1463 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1470 if (FirstD == FirstPath->Decls.second &&
1471 CurrentD == Path->Decls.second)
1475 R.setAmbiguousBaseSubobjectTypes(Paths);
1479 if (SubobjectNumber != PathElement.SubobjectNumber) {
1480 // We have a different subobject of the same type.
1482 // C++ [class.member.lookup]p5:
1483 // A static member, a nested type or an enumerator defined in
1484 // a base class T can unambiguously be found even if an object
1485 // has more than one base class subobject of type T.
1486 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
1489 // We have found a nonstatic member name in multiple, distinct
1490 // subobjects. Name lookup is ambiguous.
1491 R.setAmbiguousBaseSubobjects(Paths);
1496 // Lookup in a base class succeeded; return these results.
1498 DeclContext::lookup_iterator I, E;
1499 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1501 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1509 /// @brief Performs name lookup for a name that was parsed in the
1510 /// source code, and may contain a C++ scope specifier.
1512 /// This routine is a convenience routine meant to be called from
1513 /// contexts that receive a name and an optional C++ scope specifier
1514 /// (e.g., "N::M::x"). It will then perform either qualified or
1515 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1516 /// respectively) on the given name and return those results.
1518 /// @param S The scope from which unqualified name lookup will
1521 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1523 /// @param EnteringContext Indicates whether we are going to enter the
1524 /// context of the scope-specifier SS (if present).
1526 /// @returns True if any decls were found (but possibly ambiguous)
1527 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1528 bool AllowBuiltinCreation, bool EnteringContext) {
1529 if (SS && SS->isInvalid()) {
1530 // When the scope specifier is invalid, don't even look for
1535 if (SS && SS->isSet()) {
1536 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1537 // We have resolved the scope specifier to a particular declaration
1538 // contex, and will perform name lookup in that context.
1539 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1542 R.setContextRange(SS->getRange());
1544 return LookupQualifiedName(R, DC);
1547 // We could not resolve the scope specified to a specific declaration
1548 // context, which means that SS refers to an unknown specialization.
1549 // Name lookup can't find anything in this case.
1553 // Perform unqualified name lookup starting in the given scope.
1554 return LookupName(R, S, AllowBuiltinCreation);
1558 /// @brief Produce a diagnostic describing the ambiguity that resulted
1559 /// from name lookup.
1561 /// @param Result The ambiguous name lookup result.
1563 /// @param Name The name of the entity that name lookup was
1566 /// @param NameLoc The location of the name within the source code.
1568 /// @param LookupRange A source range that provides more
1569 /// source-location information concerning the lookup itself. For
1570 /// example, this range might highlight a nested-name-specifier that
1571 /// precedes the name.
1574 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1575 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1577 DeclarationName Name = Result.getLookupName();
1578 SourceLocation NameLoc = Result.getNameLoc();
1579 SourceRange LookupRange = Result.getContextRange();
1581 switch (Result.getAmbiguityKind()) {
1582 case LookupResult::AmbiguousBaseSubobjects: {
1583 CXXBasePaths *Paths = Result.getBasePaths();
1584 QualType SubobjectType = Paths->front().back().Base->getType();
1585 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1586 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1589 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1590 while (isa<CXXMethodDecl>(*Found) &&
1591 cast<CXXMethodDecl>(*Found)->isStatic())
1594 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1599 case LookupResult::AmbiguousBaseSubobjectTypes: {
1600 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1601 << Name << LookupRange;
1603 CXXBasePaths *Paths = Result.getBasePaths();
1604 std::set<Decl *> DeclsPrinted;
1605 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1606 PathEnd = Paths->end();
1607 Path != PathEnd; ++Path) {
1608 Decl *D = *Path->Decls.first;
1609 if (DeclsPrinted.insert(D).second)
1610 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1616 case LookupResult::AmbiguousTagHiding: {
1617 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1619 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1621 LookupResult::iterator DI, DE = Result.end();
1622 for (DI = Result.begin(); DI != DE; ++DI)
1623 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1624 TagDecls.insert(TD);
1625 Diag(TD->getLocation(), diag::note_hidden_tag);
1628 for (DI = Result.begin(); DI != DE; ++DI)
1629 if (!isa<TagDecl>(*DI))
1630 Diag((*DI)->getLocation(), diag::note_hiding_object);
1632 // For recovery purposes, go ahead and implement the hiding.
1633 LookupResult::Filter F = Result.makeFilter();
1634 while (F.hasNext()) {
1635 if (TagDecls.count(F.next()))
1643 case LookupResult::AmbiguousReference: {
1644 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1646 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1647 for (; DI != DE; ++DI)
1648 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1654 llvm_unreachable("unknown ambiguity kind");
1659 struct AssociatedLookup {
1660 AssociatedLookup(Sema &S,
1661 Sema::AssociatedNamespaceSet &Namespaces,
1662 Sema::AssociatedClassSet &Classes)
1663 : S(S), Namespaces(Namespaces), Classes(Classes) {
1667 Sema::AssociatedNamespaceSet &Namespaces;
1668 Sema::AssociatedClassSet &Classes;
1673 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1675 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1677 // Add the associated namespace for this class.
1679 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1680 // be a locally scoped record.
1682 // We skip out of inline namespaces. The innermost non-inline namespace
1683 // contains all names of all its nested inline namespaces anyway, so we can
1684 // replace the entire inline namespace tree with its root.
1685 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1686 Ctx->isInlineNamespace())
1687 Ctx = Ctx->getParent();
1689 if (Ctx->isFileContext())
1690 Namespaces.insert(Ctx->getPrimaryContext());
1693 // \brief Add the associated classes and namespaces for argument-dependent
1694 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1696 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1697 const TemplateArgument &Arg) {
1698 // C++ [basic.lookup.koenig]p2, last bullet:
1700 switch (Arg.getKind()) {
1701 case TemplateArgument::Null:
1704 case TemplateArgument::Type:
1705 // [...] the namespaces and classes associated with the types of the
1706 // template arguments provided for template type parameters (excluding
1707 // template template parameters)
1708 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1711 case TemplateArgument::Template:
1712 case TemplateArgument::TemplateExpansion: {
1713 // [...] the namespaces in which any template template arguments are
1714 // defined; and the classes in which any member templates used as
1715 // template template arguments are defined.
1716 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1717 if (ClassTemplateDecl *ClassTemplate
1718 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1719 DeclContext *Ctx = ClassTemplate->getDeclContext();
1720 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1721 Result.Classes.insert(EnclosingClass);
1722 // Add the associated namespace for this class.
1723 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1728 case TemplateArgument::Declaration:
1729 case TemplateArgument::Integral:
1730 case TemplateArgument::Expression:
1731 // [Note: non-type template arguments do not contribute to the set of
1732 // associated namespaces. ]
1735 case TemplateArgument::Pack:
1736 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1737 PEnd = Arg.pack_end();
1739 addAssociatedClassesAndNamespaces(Result, *P);
1744 // \brief Add the associated classes and namespaces for
1745 // argument-dependent lookup with an argument of class type
1746 // (C++ [basic.lookup.koenig]p2).
1748 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1749 CXXRecordDecl *Class) {
1751 // Just silently ignore anything whose name is __va_list_tag.
1752 if (Class->getDeclName() == Result.S.VAListTagName)
1755 // C++ [basic.lookup.koenig]p2:
1757 // -- If T is a class type (including unions), its associated
1758 // classes are: the class itself; the class of which it is a
1759 // member, if any; and its direct and indirect base
1760 // classes. Its associated namespaces are the namespaces in
1761 // which its associated classes are defined.
1763 // Add the class of which it is a member, if any.
1764 DeclContext *Ctx = Class->getDeclContext();
1765 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1766 Result.Classes.insert(EnclosingClass);
1767 // Add the associated namespace for this class.
1768 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1770 // Add the class itself. If we've already seen this class, we don't
1771 // need to visit base classes.
1772 if (!Result.Classes.insert(Class))
1775 // -- If T is a template-id, its associated namespaces and classes are
1776 // the namespace in which the template is defined; for member
1777 // templates, the member template's class; the namespaces and classes
1778 // associated with the types of the template arguments provided for
1779 // template type parameters (excluding template template parameters); the
1780 // namespaces in which any template template arguments are defined; and
1781 // the classes in which any member templates used as template template
1782 // arguments are defined. [Note: non-type template arguments do not
1783 // contribute to the set of associated namespaces. ]
1784 if (ClassTemplateSpecializationDecl *Spec
1785 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1786 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1787 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1788 Result.Classes.insert(EnclosingClass);
1789 // Add the associated namespace for this class.
1790 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1792 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1793 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1794 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
1797 // Only recurse into base classes for complete types.
1798 if (!Class->hasDefinition()) {
1799 // FIXME: we might need to instantiate templates here
1803 // Add direct and indirect base classes along with their associated
1805 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1806 Bases.push_back(Class);
1807 while (!Bases.empty()) {
1808 // Pop this class off the stack.
1809 Class = Bases.back();
1812 // Visit the base classes.
1813 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1814 BaseEnd = Class->bases_end();
1815 Base != BaseEnd; ++Base) {
1816 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1817 // In dependent contexts, we do ADL twice, and the first time around,
1818 // the base type might be a dependent TemplateSpecializationType, or a
1819 // TemplateTypeParmType. If that happens, simply ignore it.
1820 // FIXME: If we want to support export, we probably need to add the
1821 // namespace of the template in a TemplateSpecializationType, or even
1822 // the classes and namespaces of known non-dependent arguments.
1825 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1826 if (Result.Classes.insert(BaseDecl)) {
1827 // Find the associated namespace for this base class.
1828 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1829 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
1831 // Make sure we visit the bases of this base class.
1832 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1833 Bases.push_back(BaseDecl);
1839 // \brief Add the associated classes and namespaces for
1840 // argument-dependent lookup with an argument of type T
1841 // (C++ [basic.lookup.koenig]p2).
1843 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
1844 // C++ [basic.lookup.koenig]p2:
1846 // For each argument type T in the function call, there is a set
1847 // of zero or more associated namespaces and a set of zero or more
1848 // associated classes to be considered. The sets of namespaces and
1849 // classes is determined entirely by the types of the function
1850 // arguments (and the namespace of any template template
1851 // argument). Typedef names and using-declarations used to specify
1852 // the types do not contribute to this set. The sets of namespaces
1853 // and classes are determined in the following way:
1855 llvm::SmallVector<const Type *, 16> Queue;
1856 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1859 switch (T->getTypeClass()) {
1861 #define TYPE(Class, Base)
1862 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1863 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1864 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1865 #define ABSTRACT_TYPE(Class, Base)
1866 #include "clang/AST/TypeNodes.def"
1867 // T is canonical. We can also ignore dependent types because
1868 // we don't need to do ADL at the definition point, but if we
1869 // wanted to implement template export (or if we find some other
1870 // use for associated classes and namespaces...) this would be
1874 // -- If T is a pointer to U or an array of U, its associated
1875 // namespaces and classes are those associated with U.
1877 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1879 case Type::ConstantArray:
1880 case Type::IncompleteArray:
1881 case Type::VariableArray:
1882 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1885 // -- If T is a fundamental type, its associated sets of
1886 // namespaces and classes are both empty.
1890 // -- If T is a class type (including unions), its associated
1891 // classes are: the class itself; the class of which it is a
1892 // member, if any; and its direct and indirect base
1893 // classes. Its associated namespaces are the namespaces in
1894 // which its associated classes are defined.
1895 case Type::Record: {
1896 CXXRecordDecl *Class
1897 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
1898 addAssociatedClassesAndNamespaces(Result, Class);
1902 // -- If T is an enumeration type, its associated namespace is
1903 // the namespace in which it is defined. If it is class
1904 // member, its associated class is the member's class; else
1905 // it has no associated class.
1907 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
1909 DeclContext *Ctx = Enum->getDeclContext();
1910 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1911 Result.Classes.insert(EnclosingClass);
1913 // Add the associated namespace for this class.
1914 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1919 // -- If T is a function type, its associated namespaces and
1920 // classes are those associated with the function parameter
1921 // types and those associated with the return type.
1922 case Type::FunctionProto: {
1923 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1924 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1925 ArgEnd = Proto->arg_type_end();
1926 Arg != ArgEnd; ++Arg)
1927 Queue.push_back(Arg->getTypePtr());
1930 case Type::FunctionNoProto: {
1931 const FunctionType *FnType = cast<FunctionType>(T);
1932 T = FnType->getResultType().getTypePtr();
1936 // -- If T is a pointer to a member function of a class X, its
1937 // associated namespaces and classes are those associated
1938 // with the function parameter types and return type,
1939 // together with those associated with X.
1941 // -- If T is a pointer to a data member of class X, its
1942 // associated namespaces and classes are those associated
1943 // with the member type together with those associated with
1945 case Type::MemberPointer: {
1946 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1948 // Queue up the class type into which this points.
1949 Queue.push_back(MemberPtr->getClass());
1951 // And directly continue with the pointee type.
1952 T = MemberPtr->getPointeeType().getTypePtr();
1956 // As an extension, treat this like a normal pointer.
1957 case Type::BlockPointer:
1958 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1961 // References aren't covered by the standard, but that's such an
1962 // obvious defect that we cover them anyway.
1963 case Type::LValueReference:
1964 case Type::RValueReference:
1965 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1968 // These are fundamental types.
1970 case Type::ExtVector:
1974 // If T is an Objective-C object or interface type, or a pointer to an
1975 // object or interface type, the associated namespace is the global
1977 case Type::ObjCObject:
1978 case Type::ObjCInterface:
1979 case Type::ObjCObjectPointer:
1980 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
1984 if (Queue.empty()) break;
1990 /// \brief Find the associated classes and namespaces for
1991 /// argument-dependent lookup for a call with the given set of
1994 /// This routine computes the sets of associated classes and associated
1995 /// namespaces searched by argument-dependent lookup
1996 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1998 Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1999 AssociatedNamespaceSet &AssociatedNamespaces,
2000 AssociatedClassSet &AssociatedClasses) {
2001 AssociatedNamespaces.clear();
2002 AssociatedClasses.clear();
2004 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
2006 // C++ [basic.lookup.koenig]p2:
2007 // For each argument type T in the function call, there is a set
2008 // of zero or more associated namespaces and a set of zero or more
2009 // associated classes to be considered. The sets of namespaces and
2010 // classes is determined entirely by the types of the function
2011 // arguments (and the namespace of any template template
2013 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
2014 Expr *Arg = Args[ArgIdx];
2016 if (Arg->getType() != Context.OverloadTy) {
2017 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2021 // [...] In addition, if the argument is the name or address of a
2022 // set of overloaded functions and/or function templates, its
2023 // associated classes and namespaces are the union of those
2024 // associated with each of the members of the set: the namespace
2025 // in which the function or function template is defined and the
2026 // classes and namespaces associated with its (non-dependent)
2027 // parameter types and return type.
2028 Arg = Arg->IgnoreParens();
2029 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2030 if (unaryOp->getOpcode() == UO_AddrOf)
2031 Arg = unaryOp->getSubExpr();
2033 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2036 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2038 // Look through any using declarations to find the underlying function.
2039 NamedDecl *Fn = (*I)->getUnderlyingDecl();
2041 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2043 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2045 // Add the classes and namespaces associated with the parameter
2046 // types and return type of this function.
2047 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2052 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2053 /// an acceptable non-member overloaded operator for a call whose
2054 /// arguments have types T1 (and, if non-empty, T2). This routine
2055 /// implements the check in C++ [over.match.oper]p3b2 concerning
2056 /// enumeration types.
2058 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2059 QualType T1, QualType T2,
2060 ASTContext &Context) {
2061 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2064 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2067 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2068 if (Proto->getNumArgs() < 1)
2071 if (T1->isEnumeralType()) {
2072 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2073 if (Context.hasSameUnqualifiedType(T1, ArgType))
2077 if (Proto->getNumArgs() < 2)
2080 if (!T2.isNull() && T2->isEnumeralType()) {
2081 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2082 if (Context.hasSameUnqualifiedType(T2, ArgType))
2089 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2091 LookupNameKind NameKind,
2092 RedeclarationKind Redecl) {
2093 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2095 return R.getAsSingle<NamedDecl>();
2098 /// \brief Find the protocol with the given name, if any.
2099 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2100 SourceLocation IdLoc) {
2101 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2102 LookupObjCProtocolName);
2103 return cast_or_null<ObjCProtocolDecl>(D);
2106 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2107 QualType T1, QualType T2,
2108 UnresolvedSetImpl &Functions) {
2109 // C++ [over.match.oper]p3:
2110 // -- The set of non-member candidates is the result of the
2111 // unqualified lookup of operator@ in the context of the
2112 // expression according to the usual rules for name lookup in
2113 // unqualified function calls (3.4.2) except that all member
2114 // functions are ignored. However, if no operand has a class
2115 // type, only those non-member functions in the lookup set
2116 // that have a first parameter of type T1 or "reference to
2117 // (possibly cv-qualified) T1", when T1 is an enumeration
2118 // type, or (if there is a right operand) a second parameter
2119 // of type T2 or "reference to (possibly cv-qualified) T2",
2120 // when T2 is an enumeration type, are candidate functions.
2121 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2122 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2123 LookupName(Operators, S);
2125 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2127 if (Operators.empty())
2130 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2131 Op != OpEnd; ++Op) {
2132 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2133 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2134 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2135 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2136 } else if (FunctionTemplateDecl *FunTmpl
2137 = dyn_cast<FunctionTemplateDecl>(Found)) {
2138 // FIXME: friend operators?
2139 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2141 if (!FunTmpl->getDeclContext()->isRecord())
2142 Functions.addDecl(*Op, Op.getAccess());
2147 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
2148 CXXSpecialMember SM,
2153 bool VolatileThis) {
2154 RD = RD->getDefinition();
2155 assert((RD && !RD->isBeingDefined()) &&
2156 "doing special member lookup into record that isn't fully complete");
2157 if (RValueThis || ConstThis || VolatileThis)
2158 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2159 "constructors and destructors always have unqualified lvalue this");
2160 if (ConstArg || VolatileArg)
2161 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2162 "parameter-less special members can't have qualified arguments");
2164 llvm::FoldingSetNodeID ID;
2167 ID.AddInteger(ConstArg);
2168 ID.AddInteger(VolatileArg);
2169 ID.AddInteger(RValueThis);
2170 ID.AddInteger(ConstThis);
2171 ID.AddInteger(VolatileThis);
2174 SpecialMemberOverloadResult *Result =
2175 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2177 // This was already cached
2181 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2182 Result = new (Result) SpecialMemberOverloadResult(ID);
2183 SpecialMemberCache.InsertNode(Result, InsertPoint);
2185 if (SM == CXXDestructor) {
2186 if (!RD->hasDeclaredDestructor())
2187 DeclareImplicitDestructor(RD);
2188 CXXDestructorDecl *DD = RD->getDestructor();
2189 assert(DD && "record without a destructor");
2190 Result->setMethod(DD);
2191 Result->setSuccess(DD->isDeleted());
2192 Result->setConstParamMatch(false);
2196 // Prepare for overload resolution. Here we construct a synthetic argument
2197 // if necessary and make sure that implicit functions are declared.
2198 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2199 DeclarationName Name;
2203 if (SM == CXXDefaultConstructor) {
2204 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2206 if (RD->needsImplicitDefaultConstructor())
2207 DeclareImplicitDefaultConstructor(RD);
2209 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2210 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2211 if (!RD->hasDeclaredCopyConstructor())
2212 DeclareImplicitCopyConstructor(RD);
2213 // TODO: Move constructors
2215 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2216 if (!RD->hasDeclaredCopyAssignment())
2217 DeclareImplicitCopyAssignment(RD);
2218 // TODO: Move assignment
2221 QualType ArgType = CanTy;
2225 ArgType.addVolatile();
2227 // This isn't /really/ specified by the standard, but it's implied
2228 // we should be working from an RValue in the case of move to ensure
2229 // that we prefer to bind to rvalue references, and an LValue in the
2230 // case of copy to ensure we don't bind to rvalue references.
2231 // Possibly an XValue is actually correct in the case of move, but
2232 // there is no semantic difference for class types in this restricted
2235 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2241 Arg = new (Context) OpaqueValueExpr(SourceLocation(), ArgType, VK);
2244 // Create the object argument
2245 QualType ThisTy = CanTy;
2249 ThisTy.addVolatile();
2250 Expr::Classification Classification =
2251 (new (Context) OpaqueValueExpr(SourceLocation(), ThisTy,
2252 RValueThis ? VK_RValue : VK_LValue))->
2255 // Now we perform lookup on the name we computed earlier and do overload
2256 // resolution. Lookup is only performed directly into the class since there
2257 // will always be a (possibly implicit) declaration to shadow any others.
2258 OverloadCandidateSet OCS((SourceLocation()));
2259 DeclContext::lookup_iterator I, E;
2260 Result->setConstParamMatch(false);
2262 llvm::tie(I, E) = RD->lookup(Name);
2264 "lookup for a constructor or assignment operator was empty");
2265 for ( ; I != E; ++I) {
2268 if (Cand->isInvalidDecl())
2271 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2272 // FIXME: [namespace.udecl]p15 says that we should only consider a
2273 // using declaration here if it does not match a declaration in the
2274 // derived class. We do not implement this correctly in other cases
2276 Cand = U->getTargetDecl();
2278 if (Cand->isInvalidDecl())
2282 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
2283 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2284 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
2285 Classification, &Arg, NumArgs, OCS, true);
2287 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public), &Arg,
2288 NumArgs, OCS, true);
2290 // Here we're looking for a const parameter to speed up creation of
2291 // implicit copy methods.
2292 if ((SM == CXXCopyAssignment && M->isCopyAssignmentOperator()) ||
2293 (SM == CXXCopyConstructor &&
2294 cast<CXXConstructorDecl>(M)->isCopyConstructor())) {
2295 QualType ArgType = M->getType()->getAs<FunctionProtoType>()->getArgType(0);
2296 if (!ArgType->isReferenceType() ||
2297 ArgType->getPointeeType().isConstQualified())
2298 Result->setConstParamMatch(true);
2300 } else if (FunctionTemplateDecl *Tmpl =
2301 dyn_cast<FunctionTemplateDecl>(Cand)) {
2302 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2303 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2304 RD, 0, ThisTy, Classification, &Arg, NumArgs,
2307 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2308 0, &Arg, NumArgs, OCS, true);
2310 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
2314 OverloadCandidateSet::iterator Best;
2315 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2317 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2318 Result->setSuccess(true);
2322 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2323 Result->setSuccess(false);
2327 case OR_No_Viable_Function:
2328 Result->setMethod(0);
2329 Result->setSuccess(false);
2336 /// \brief Look up the default constructor for the given class.
2337 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
2338 SpecialMemberOverloadResult *Result =
2339 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2342 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2345 /// \brief Look up the copying constructor for the given class.
2346 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2348 bool *ConstParamMatch) {
2349 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2350 "non-const, non-volatile qualifiers for copy ctor arg");
2351 SpecialMemberOverloadResult *Result =
2352 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2353 Quals & Qualifiers::Volatile, false, false, false);
2355 if (ConstParamMatch)
2356 *ConstParamMatch = Result->hasConstParamMatch();
2358 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2361 /// \brief Look up the constructors for the given class.
2362 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2363 // If the implicit constructors have not yet been declared, do so now.
2364 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2365 if (Class->needsImplicitDefaultConstructor())
2366 DeclareImplicitDefaultConstructor(Class);
2367 if (!Class->hasDeclaredCopyConstructor())
2368 DeclareImplicitCopyConstructor(Class);
2371 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2372 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2373 return Class->lookup(Name);
2376 /// \brief Look up the copying assignment operator for the given class.
2377 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2378 unsigned Quals, bool RValueThis,
2380 bool *ConstParamMatch) {
2381 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2382 "non-const, non-volatile qualifiers for copy assignment arg");
2383 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2384 "non-const, non-volatile qualifiers for copy assignment this");
2385 SpecialMemberOverloadResult *Result =
2386 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2387 Quals & Qualifiers::Volatile, RValueThis,
2388 ThisQuals & Qualifiers::Const,
2389 ThisQuals & Qualifiers::Volatile);
2391 if (ConstParamMatch)
2392 *ConstParamMatch = Result->hasConstParamMatch();
2394 return Result->getMethod();
2397 /// \brief Look for the destructor of the given class.
2399 /// During semantic analysis, this routine should be used in lieu of
2400 /// CXXRecordDecl::getDestructor().
2402 /// \returns The destructor for this class.
2403 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2404 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2405 false, false, false,
2406 false, false)->getMethod());
2409 void ADLResult::insert(NamedDecl *New) {
2410 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2412 // If we haven't yet seen a decl for this key, or the last decl
2413 // was exactly this one, we're done.
2414 if (Old == 0 || Old == New) {
2419 // Otherwise, decide which is a more recent redeclaration.
2420 FunctionDecl *OldFD, *NewFD;
2421 if (isa<FunctionTemplateDecl>(New)) {
2422 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2423 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2425 OldFD = cast<FunctionDecl>(Old);
2426 NewFD = cast<FunctionDecl>(New);
2429 FunctionDecl *Cursor = NewFD;
2431 Cursor = Cursor->getPreviousDeclaration();
2433 // If we got to the end without finding OldFD, OldFD is the newer
2434 // declaration; leave things as they are.
2435 if (!Cursor) return;
2437 // If we do find OldFD, then NewFD is newer.
2438 if (Cursor == OldFD) break;
2440 // Otherwise, keep looking.
2446 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2447 Expr **Args, unsigned NumArgs,
2449 bool StdNamespaceIsAssociated) {
2450 // Find all of the associated namespaces and classes based on the
2451 // arguments we have.
2452 AssociatedNamespaceSet AssociatedNamespaces;
2453 AssociatedClassSet AssociatedClasses;
2454 FindAssociatedClassesAndNamespaces(Args, NumArgs,
2455 AssociatedNamespaces,
2457 if (StdNamespaceIsAssociated && StdNamespace)
2458 AssociatedNamespaces.insert(getStdNamespace());
2462 T1 = Args[0]->getType();
2464 T2 = Args[1]->getType();
2467 // C++ [basic.lookup.argdep]p3:
2468 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2469 // and let Y be the lookup set produced by argument dependent
2470 // lookup (defined as follows). If X contains [...] then Y is
2471 // empty. Otherwise Y is the set of declarations found in the
2472 // namespaces associated with the argument types as described
2473 // below. The set of declarations found by the lookup of the name
2474 // is the union of X and Y.
2476 // Here, we compute Y and add its members to the overloaded
2478 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2479 NSEnd = AssociatedNamespaces.end();
2480 NS != NSEnd; ++NS) {
2481 // When considering an associated namespace, the lookup is the
2482 // same as the lookup performed when the associated namespace is
2483 // used as a qualifier (3.4.3.2) except that:
2485 // -- Any using-directives in the associated namespace are
2488 // -- Any namespace-scope friend functions declared in
2489 // associated classes are visible within their respective
2490 // namespaces even if they are not visible during an ordinary
2492 DeclContext::lookup_iterator I, E;
2493 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
2495 // If the only declaration here is an ordinary friend, consider
2496 // it only if it was declared in an associated classes.
2497 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
2498 DeclContext *LexDC = D->getLexicalDeclContext();
2499 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2503 if (isa<UsingShadowDecl>(D))
2504 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2506 if (isa<FunctionDecl>(D)) {
2508 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2511 } else if (!isa<FunctionTemplateDecl>(D))
2519 //----------------------------------------------------------------------------
2520 // Search for all visible declarations.
2521 //----------------------------------------------------------------------------
2522 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2526 class ShadowContextRAII;
2528 class VisibleDeclsRecord {
2530 /// \brief An entry in the shadow map, which is optimized to store a
2531 /// single declaration (the common case) but can also store a list
2532 /// of declarations.
2533 class ShadowMapEntry {
2534 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2536 /// \brief Contains either the solitary NamedDecl * or a vector
2537 /// of declarations.
2538 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2541 ShadowMapEntry() : DeclOrVector() { }
2543 void Add(NamedDecl *ND);
2547 typedef NamedDecl * const *iterator;
2553 /// \brief A mapping from declaration names to the declarations that have
2554 /// this name within a particular scope.
2555 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2557 /// \brief A list of shadow maps, which is used to model name hiding.
2558 std::list<ShadowMap> ShadowMaps;
2560 /// \brief The declaration contexts we have already visited.
2561 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2563 friend class ShadowContextRAII;
2566 /// \brief Determine whether we have already visited this context
2567 /// (and, if not, note that we are going to visit that context now).
2568 bool visitedContext(DeclContext *Ctx) {
2569 return !VisitedContexts.insert(Ctx);
2572 bool alreadyVisitedContext(DeclContext *Ctx) {
2573 return VisitedContexts.count(Ctx);
2576 /// \brief Determine whether the given declaration is hidden in the
2579 /// \returns the declaration that hides the given declaration, or
2580 /// NULL if no such declaration exists.
2581 NamedDecl *checkHidden(NamedDecl *ND);
2583 /// \brief Add a declaration to the current shadow map.
2584 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2587 /// \brief RAII object that records when we've entered a shadow context.
2588 class ShadowContextRAII {
2589 VisibleDeclsRecord &Visible;
2591 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2594 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2595 Visible.ShadowMaps.push_back(ShadowMap());
2598 ~ShadowContextRAII() {
2599 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2600 EEnd = Visible.ShadowMaps.back().end();
2603 E->second.Destroy();
2605 Visible.ShadowMaps.pop_back();
2609 } // end anonymous namespace
2611 void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2612 if (DeclOrVector.isNull()) {
2613 // 0 - > 1 elements: just set the single element information.
2618 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2619 // 1 -> 2 elements: create the vector of results and push in the
2620 // existing declaration.
2621 DeclVector *Vec = new DeclVector;
2622 Vec->push_back(PrevND);
2626 // Add the new element to the end of the vector.
2627 DeclOrVector.get<DeclVector*>()->push_back(ND);
2630 void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2631 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2633 DeclOrVector = ((NamedDecl *)0);
2637 VisibleDeclsRecord::ShadowMapEntry::iterator
2638 VisibleDeclsRecord::ShadowMapEntry::begin() {
2639 if (DeclOrVector.isNull())
2642 if (DeclOrVector.is<NamedDecl *>())
2643 return DeclOrVector.getAddrOf<NamedDecl *>();
2645 return DeclOrVector.get<DeclVector *>()->begin();
2648 VisibleDeclsRecord::ShadowMapEntry::iterator
2649 VisibleDeclsRecord::ShadowMapEntry::end() {
2650 if (DeclOrVector.isNull())
2653 if (DeclOrVector.is<NamedDecl *>())
2654 return DeclOrVector.getAddrOf<NamedDecl *>() + 1;
2656 return DeclOrVector.get<DeclVector *>()->end();
2659 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2660 // Look through using declarations.
2661 ND = ND->getUnderlyingDecl();
2663 unsigned IDNS = ND->getIdentifierNamespace();
2664 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2665 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2666 SM != SMEnd; ++SM) {
2667 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2668 if (Pos == SM->end())
2671 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2672 IEnd = Pos->second.end();
2674 // A tag declaration does not hide a non-tag declaration.
2675 if ((*I)->hasTagIdentifierNamespace() &&
2676 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2677 Decl::IDNS_ObjCProtocol)))
2680 // Protocols are in distinct namespaces from everything else.
2681 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2682 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2683 (*I)->getIdentifierNamespace() != IDNS)
2686 // Functions and function templates in the same scope overload
2687 // rather than hide. FIXME: Look for hiding based on function
2689 if ((*I)->isFunctionOrFunctionTemplate() &&
2690 ND->isFunctionOrFunctionTemplate() &&
2691 SM == ShadowMaps.rbegin())
2694 // We've found a declaration that hides this one.
2702 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2703 bool QualifiedNameLookup,
2705 VisibleDeclConsumer &Consumer,
2706 VisibleDeclsRecord &Visited) {
2710 // Make sure we don't visit the same context twice.
2711 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2714 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2715 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2717 // Enumerate all of the results in this context.
2718 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2719 CurCtx = CurCtx->getNextContext()) {
2720 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2721 DEnd = CurCtx->decls_end();
2723 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
2724 if (Result.isAcceptableDecl(ND)) {
2725 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
2728 } else if (ObjCForwardProtocolDecl *ForwardProto
2729 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2730 for (ObjCForwardProtocolDecl::protocol_iterator
2731 P = ForwardProto->protocol_begin(),
2732 PEnd = ForwardProto->protocol_end();
2735 if (Result.isAcceptableDecl(*P)) {
2736 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2740 } else if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) {
2741 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
2743 ObjCInterfaceDecl *IFace = I->getInterface();
2744 if (Result.isAcceptableDecl(IFace)) {
2745 Consumer.FoundDecl(IFace, Visited.checkHidden(IFace), InBaseClass);
2751 // Visit transparent contexts and inline namespaces inside this context.
2752 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2753 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
2754 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
2760 // Traverse using directives for qualified name lookup.
2761 if (QualifiedNameLookup) {
2762 ShadowContextRAII Shadow(Visited);
2763 DeclContext::udir_iterator I, E;
2764 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2765 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
2766 QualifiedNameLookup, InBaseClass, Consumer, Visited);
2770 // Traverse the contexts of inherited C++ classes.
2771 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2772 if (!Record->hasDefinition())
2775 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2776 BEnd = Record->bases_end();
2778 QualType BaseType = B->getType();
2780 // Don't look into dependent bases, because name lookup can't look
2782 if (BaseType->isDependentType())
2785 const RecordType *Record = BaseType->getAs<RecordType>();
2789 // FIXME: It would be nice to be able to determine whether referencing
2790 // a particular member would be ambiguous. For example, given
2792 // struct A { int member; };
2793 // struct B { int member; };
2794 // struct C : A, B { };
2796 // void f(C *c) { c->### }
2798 // accessing 'member' would result in an ambiguity. However, we
2799 // could be smart enough to qualify the member with the base
2808 // Find results in this base class (and its bases).
2809 ShadowContextRAII Shadow(Visited);
2810 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2811 true, Consumer, Visited);
2815 // Traverse the contexts of Objective-C classes.
2816 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2817 // Traverse categories.
2818 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2819 Category; Category = Category->getNextClassCategory()) {
2820 ShadowContextRAII Shadow(Visited);
2821 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2825 // Traverse protocols.
2826 for (ObjCInterfaceDecl::all_protocol_iterator
2827 I = IFace->all_referenced_protocol_begin(),
2828 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
2829 ShadowContextRAII Shadow(Visited);
2830 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2834 // Traverse the superclass.
2835 if (IFace->getSuperClass()) {
2836 ShadowContextRAII Shadow(Visited);
2837 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
2838 true, Consumer, Visited);
2841 // If there is an implementation, traverse it. We do this to find
2842 // synthesized ivars.
2843 if (IFace->getImplementation()) {
2844 ShadowContextRAII Shadow(Visited);
2845 LookupVisibleDecls(IFace->getImplementation(), Result,
2846 QualifiedNameLookup, true, Consumer, Visited);
2848 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2849 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2850 E = Protocol->protocol_end(); I != E; ++I) {
2851 ShadowContextRAII Shadow(Visited);
2852 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2855 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2856 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2857 E = Category->protocol_end(); I != E; ++I) {
2858 ShadowContextRAII Shadow(Visited);
2859 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2863 // If there is an implementation, traverse it.
2864 if (Category->getImplementation()) {
2865 ShadowContextRAII Shadow(Visited);
2866 LookupVisibleDecls(Category->getImplementation(), Result,
2867 QualifiedNameLookup, true, Consumer, Visited);
2872 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2873 UnqualUsingDirectiveSet &UDirs,
2874 VisibleDeclConsumer &Consumer,
2875 VisibleDeclsRecord &Visited) {
2879 if (!S->getEntity() ||
2881 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
2882 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2883 // Walk through the declarations in this Scope.
2884 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2886 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2887 if (Result.isAcceptableDecl(ND)) {
2888 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
2894 // FIXME: C++ [temp.local]p8
2895 DeclContext *Entity = 0;
2896 if (S->getEntity()) {
2897 // Look into this scope's declaration context, along with any of its
2898 // parent lookup contexts (e.g., enclosing classes), up to the point
2899 // where we hit the context stored in the next outer scope.
2900 Entity = (DeclContext *)S->getEntity();
2901 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
2903 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
2904 Ctx = Ctx->getLookupParent()) {
2905 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2906 if (Method->isInstanceMethod()) {
2907 // For instance methods, look for ivars in the method's interface.
2908 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2909 Result.getNameLoc(), Sema::LookupMemberName);
2910 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
2911 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2912 /*InBaseClass=*/false, Consumer, Visited);
2914 // Look for properties from which we can synthesize ivars, if
2916 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2917 IFace->getImplementation() &&
2918 Result.getLookupKind() == Sema::LookupOrdinaryName) {
2919 for (ObjCInterfaceDecl::prop_iterator
2920 P = IFace->prop_begin(),
2921 PEnd = IFace->prop_end();
2923 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2924 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2925 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2933 // We've already performed all of the name lookup that we need
2934 // to for Objective-C methods; the next context will be the
2939 if (Ctx->isFunctionOrMethod())
2942 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
2943 /*InBaseClass=*/false, Consumer, Visited);
2945 } else if (!S->getParent()) {
2946 // Look into the translation unit scope. We walk through the translation
2947 // unit's declaration context, because the Scope itself won't have all of
2948 // the declarations if we loaded a precompiled header.
2949 // FIXME: We would like the translation unit's Scope object to point to the
2950 // translation unit, so we don't need this special "if" branch. However,
2951 // doing so would force the normal C++ name-lookup code to look into the
2952 // translation unit decl when the IdentifierInfo chains would suffice.
2953 // Once we fix that problem (which is part of a more general "don't look
2954 // in DeclContexts unless we have to" optimization), we can eliminate this.
2955 Entity = Result.getSema().Context.getTranslationUnitDecl();
2956 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
2957 /*InBaseClass=*/false, Consumer, Visited);
2961 // Lookup visible declarations in any namespaces found by using
2963 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2964 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2965 for (; UI != UEnd; ++UI)
2966 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
2967 Result, /*QualifiedNameLookup=*/false,
2968 /*InBaseClass=*/false, Consumer, Visited);
2971 // Lookup names in the parent scope.
2972 ShadowContextRAII Shadow(Visited);
2973 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2976 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2977 VisibleDeclConsumer &Consumer,
2978 bool IncludeGlobalScope) {
2979 // Determine the set of using directives available during
2980 // unqualified name lookup.
2982 UnqualUsingDirectiveSet UDirs;
2983 if (getLangOptions().CPlusPlus) {
2984 // Find the first namespace or translation-unit scope.
2985 while (S && !isNamespaceOrTranslationUnitScope(S))
2988 UDirs.visitScopeChain(Initial, S);
2992 // Look for visible declarations.
2993 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2994 VisibleDeclsRecord Visited;
2995 if (!IncludeGlobalScope)
2996 Visited.visitedContext(Context.getTranslationUnitDecl());
2997 ShadowContextRAII Shadow(Visited);
2998 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3001 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3002 VisibleDeclConsumer &Consumer,
3003 bool IncludeGlobalScope) {
3004 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3005 VisibleDeclsRecord Visited;
3006 if (!IncludeGlobalScope)
3007 Visited.visitedContext(Context.getTranslationUnitDecl());
3008 ShadowContextRAII Shadow(Visited);
3009 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3010 /*InBaseClass=*/false, Consumer, Visited);
3013 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3014 /// If GnuLabelLoc is a valid source location, then this is a definition
3015 /// of an __label__ label name, otherwise it is a normal label definition
3017 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3018 SourceLocation GnuLabelLoc) {
3019 // Do a lookup to see if we have a label with this name already.
3022 if (GnuLabelLoc.isValid()) {
3023 // Local label definitions always shadow existing labels.
3024 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3025 Scope *S = CurScope;
3026 PushOnScopeChains(Res, S, true);
3027 return cast<LabelDecl>(Res);
3030 // Not a GNU local label.
3031 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3032 // If we found a label, check to see if it is in the same context as us.
3033 // When in a Block, we don't want to reuse a label in an enclosing function.
3034 if (Res && Res->getDeclContext() != CurContext)
3037 // If not forward referenced or defined already, create the backing decl.
3038 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3039 Scope *S = CurScope->getFnParent();
3040 assert(S && "Not in a function?");
3041 PushOnScopeChains(Res, S, true);
3043 return cast<LabelDecl>(Res);
3046 //===----------------------------------------------------------------------===//
3048 //===----------------------------------------------------------------------===//
3052 typedef llvm::StringMap<TypoCorrection, llvm::BumpPtrAllocator> TypoResultsMap;
3053 typedef std::map<unsigned, TypoResultsMap *> TypoEditDistanceMap;
3055 static const unsigned MaxTypoDistanceResultSets = 5;
3057 class TypoCorrectionConsumer : public VisibleDeclConsumer {
3058 /// \brief The name written that is a typo in the source.
3059 llvm::StringRef Typo;
3061 /// \brief The results found that have the smallest edit distance
3062 /// found (so far) with the typo name.
3064 /// The pointer value being set to the current DeclContext indicates
3065 /// whether there is a keyword with this name.
3066 TypoEditDistanceMap BestResults;
3068 /// \brief The worst of the best N edit distances found so far.
3069 unsigned MaxEditDistance;
3074 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
3075 : Typo(Typo->getName()),
3076 MaxEditDistance((std::numeric_limits<unsigned>::max)()),
3077 SemaRef(SemaRef) { }
3079 ~TypoCorrectionConsumer() {
3080 for (TypoEditDistanceMap::iterator I = BestResults.begin(),
3081 IEnd = BestResults.end();
3087 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
3088 void FoundName(llvm::StringRef Name);
3089 void addKeywordResult(llvm::StringRef Keyword);
3090 void addName(llvm::StringRef Name, NamedDecl *ND, unsigned Distance,
3091 NestedNameSpecifier *NNS=NULL);
3092 void addCorrection(TypoCorrection Correction);
3094 typedef TypoResultsMap::iterator result_iterator;
3095 typedef TypoEditDistanceMap::iterator distance_iterator;
3096 distance_iterator begin() { return BestResults.begin(); }
3097 distance_iterator end() { return BestResults.end(); }
3098 void erase(distance_iterator I) { BestResults.erase(I); }
3099 unsigned size() const { return BestResults.size(); }
3100 bool empty() const { return BestResults.empty(); }
3102 TypoCorrection &operator[](llvm::StringRef Name) {
3103 return (*BestResults.begin()->second)[Name];
3106 unsigned getMaxEditDistance() const {
3107 return MaxEditDistance;
3110 unsigned getBestEditDistance() {
3111 return (BestResults.empty()) ? MaxEditDistance : BestResults.begin()->first;
3117 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3119 // Don't consider hidden names for typo correction.
3123 // Only consider entities with identifiers for names, ignoring
3124 // special names (constructors, overloaded operators, selectors,
3126 IdentifierInfo *Name = ND->getIdentifier();
3130 FoundName(Name->getName());
3133 void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
3134 // Use a simple length-based heuristic to determine the minimum possible
3135 // edit distance. If the minimum isn't good enough, bail out early.
3136 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
3137 if (MinED > MaxEditDistance || (MinED && Typo.size() / MinED < 3))
3140 // Compute an upper bound on the allowable edit distance, so that the
3141 // edit-distance algorithm can short-circuit.
3142 unsigned UpperBound =
3143 std::min(unsigned((Typo.size() + 2) / 3), MaxEditDistance);
3145 // Compute the edit distance between the typo and the name of this
3146 // entity. If this edit distance is not worse than the best edit
3147 // distance we've seen so far, add it to the list of results.
3148 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3150 if (ED > MaxEditDistance) {
3151 // This result is worse than the best results we've seen so far;
3156 addName(Name, NULL, ED);
3159 void TypoCorrectionConsumer::addKeywordResult(llvm::StringRef Keyword) {
3160 // Compute the edit distance between the typo and this keyword.
3161 // If this edit distance is not worse than the best edit
3162 // distance we've seen so far, add it to the list of results.
3163 unsigned ED = Typo.edit_distance(Keyword);
3164 if (ED > MaxEditDistance) {
3165 // This result is worse than the best results we've seen so far;
3170 addName(Keyword, TypoCorrection::KeywordDecl(), ED);
3173 void TypoCorrectionConsumer::addName(llvm::StringRef Name,
3176 NestedNameSpecifier *NNS) {
3177 addCorrection(TypoCorrection(&SemaRef.Context.Idents.get(Name),
3178 ND, NNS, Distance));
3181 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3182 llvm::StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3183 TypoResultsMap *& Map = BestResults[Correction.getEditDistance()];
3185 Map = new TypoResultsMap;
3187 TypoCorrection &CurrentCorrection = (*Map)[Name];
3188 if (!CurrentCorrection ||
3189 // FIXME: The following should be rolled up into an operator< on
3190 // TypoCorrection with a more principled definition.
3191 CurrentCorrection.isKeyword() < Correction.isKeyword() ||
3192 Correction.getAsString(SemaRef.getLangOptions()) <
3193 CurrentCorrection.getAsString(SemaRef.getLangOptions()))
3194 CurrentCorrection = Correction;
3196 while (BestResults.size() > MaxTypoDistanceResultSets) {
3197 TypoEditDistanceMap::iterator Last = BestResults.end();
3199 delete Last->second;
3200 BestResults.erase(Last);
3206 class SpecifierInfo {
3208 DeclContext* DeclCtx;
3209 NestedNameSpecifier* NameSpecifier;
3210 unsigned EditDistance;
3212 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3213 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3216 typedef llvm::SmallVector<DeclContext*, 4> DeclContextList;
3217 typedef llvm::SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3219 class NamespaceSpecifierSet {
3220 ASTContext &Context;
3221 DeclContextList CurContextChain;
3224 SpecifierInfoList Specifiers;
3225 llvm::SmallSetVector<unsigned, 4> Distances;
3226 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3228 /// \brief Helper for building the list of DeclContexts between the current
3229 /// context and the top of the translation unit
3230 static DeclContextList BuildContextChain(DeclContext *Start);
3232 void SortNamespaces();
3235 explicit NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext)
3236 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3239 /// \brief Add the namespace to the set, computing the corresponding
3240 /// NestedNameSpecifier and its distance in the process.
3241 void AddNamespace(NamespaceDecl *ND);
3243 typedef SpecifierInfoList::iterator iterator;
3245 if (!isSorted) SortNamespaces();
3246 return Specifiers.begin();
3248 iterator end() { return Specifiers.end(); }
3253 DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
3254 assert(Start && "Bulding a context chain from a null context");
3255 DeclContextList Chain;
3256 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3257 DC = DC->getLookupParent()) {
3258 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3259 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3260 !(ND && ND->isAnonymousNamespace()))
3261 Chain.push_back(DC->getPrimaryContext());
3266 void NamespaceSpecifierSet::SortNamespaces() {
3267 llvm::SmallVector<unsigned, 4> sortedDistances;
3268 sortedDistances.append(Distances.begin(), Distances.end());
3270 if (sortedDistances.size() > 1)
3271 std::sort(sortedDistances.begin(), sortedDistances.end());
3274 for (llvm::SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
3275 DIEnd = sortedDistances.end();
3276 DI != DIEnd; ++DI) {
3277 SpecifierInfoList &SpecList = DistanceMap[*DI];
3278 Specifiers.append(SpecList.begin(), SpecList.end());
3284 void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
3285 DeclContext *Ctx = cast<DeclContext>(ND);
3286 NestedNameSpecifier *NNS = NULL;
3287 unsigned NumSpecifiers = 0;
3288 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3290 // Eliminate common elements from the two DeclContext chains
3291 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3292 CEnd = CurContextChain.rend();
3293 C != CEnd && !NamespaceDeclChain.empty() &&
3294 NamespaceDeclChain.back() == *C; ++C) {
3295 NamespaceDeclChain.pop_back();
3298 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3299 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3300 CEnd = NamespaceDeclChain.rend();
3302 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3304 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3310 Distances.insert(NumSpecifiers);
3311 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3314 /// \brief Perform name lookup for a possible result for typo correction.
3315 static void LookupPotentialTypoResult(Sema &SemaRef,
3317 IdentifierInfo *Name,
3318 Scope *S, CXXScopeSpec *SS,
3319 DeclContext *MemberContext,
3320 bool EnteringContext,
3321 Sema::CorrectTypoContext CTC) {
3322 Res.suppressDiagnostics();
3324 Res.setLookupName(Name);
3325 if (MemberContext) {
3326 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3327 if (CTC == Sema::CTC_ObjCIvarLookup) {
3328 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3335 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3342 SemaRef.LookupQualifiedName(Res, MemberContext);
3346 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3349 // Fake ivar lookup; this should really be part of
3350 // LookupParsedName.
3351 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3352 if (Method->isInstanceMethod() && Method->getClassInterface() &&
3354 (Res.isSingleResult() &&
3355 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3356 if (ObjCIvarDecl *IV
3357 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3365 /// \brief Add keywords to the consumer as possible typo corrections.
3366 static void AddKeywordsToConsumer(Sema &SemaRef,
3367 TypoCorrectionConsumer &Consumer,
3368 Scope *S, Sema::CorrectTypoContext CTC) {
3369 // Add context-dependent keywords.
3370 bool WantTypeSpecifiers = false;
3371 bool WantExpressionKeywords = false;
3372 bool WantCXXNamedCasts = false;
3373 bool WantRemainingKeywords = false;
3375 case Sema::CTC_Unknown:
3376 WantTypeSpecifiers = true;
3377 WantExpressionKeywords = true;
3378 WantCXXNamedCasts = true;
3379 WantRemainingKeywords = true;
3381 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
3382 if (Method->getClassInterface() &&
3383 Method->getClassInterface()->getSuperClass())
3384 Consumer.addKeywordResult("super");
3388 case Sema::CTC_NoKeywords:
3391 case Sema::CTC_Type:
3392 WantTypeSpecifiers = true;
3395 case Sema::CTC_ObjCMessageReceiver:
3396 Consumer.addKeywordResult("super");
3397 // Fall through to handle message receivers like expressions.
3399 case Sema::CTC_Expression:
3400 if (SemaRef.getLangOptions().CPlusPlus)
3401 WantTypeSpecifiers = true;
3402 WantExpressionKeywords = true;
3403 // Fall through to get C++ named casts.
3405 case Sema::CTC_CXXCasts:
3406 WantCXXNamedCasts = true;
3409 case Sema::CTC_ObjCPropertyLookup:
3410 // FIXME: Add "isa"?
3413 case Sema::CTC_MemberLookup:
3414 if (SemaRef.getLangOptions().CPlusPlus)
3415 Consumer.addKeywordResult("template");
3418 case Sema::CTC_ObjCIvarLookup:
3422 if (WantTypeSpecifiers) {
3423 // Add type-specifier keywords to the set of results.
3424 const char *CTypeSpecs[] = {
3425 "char", "const", "double", "enum", "float", "int", "long", "short",
3426 "signed", "struct", "union", "unsigned", "void", "volatile",
3427 "_Complex", "_Imaginary",
3428 // storage-specifiers as well
3429 "extern", "inline", "static", "typedef"
3432 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3433 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3434 Consumer.addKeywordResult(CTypeSpecs[I]);
3436 if (SemaRef.getLangOptions().C99)
3437 Consumer.addKeywordResult("restrict");
3438 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus)
3439 Consumer.addKeywordResult("bool");
3440 else if (SemaRef.getLangOptions().C99)
3441 Consumer.addKeywordResult("_Bool");
3443 if (SemaRef.getLangOptions().CPlusPlus) {
3444 Consumer.addKeywordResult("class");
3445 Consumer.addKeywordResult("typename");
3446 Consumer.addKeywordResult("wchar_t");
3448 if (SemaRef.getLangOptions().CPlusPlus0x) {
3449 Consumer.addKeywordResult("char16_t");
3450 Consumer.addKeywordResult("char32_t");
3451 Consumer.addKeywordResult("constexpr");
3452 Consumer.addKeywordResult("decltype");
3453 Consumer.addKeywordResult("thread_local");
3457 if (SemaRef.getLangOptions().GNUMode)
3458 Consumer.addKeywordResult("typeof");
3461 if (WantCXXNamedCasts && SemaRef.getLangOptions().CPlusPlus) {
3462 Consumer.addKeywordResult("const_cast");
3463 Consumer.addKeywordResult("dynamic_cast");
3464 Consumer.addKeywordResult("reinterpret_cast");
3465 Consumer.addKeywordResult("static_cast");
3468 if (WantExpressionKeywords) {
3469 Consumer.addKeywordResult("sizeof");
3470 if (SemaRef.getLangOptions().Bool || SemaRef.getLangOptions().CPlusPlus) {
3471 Consumer.addKeywordResult("false");
3472 Consumer.addKeywordResult("true");
3475 if (SemaRef.getLangOptions().CPlusPlus) {
3476 const char *CXXExprs[] = {
3477 "delete", "new", "operator", "throw", "typeid"
3479 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3480 for (unsigned I = 0; I != NumCXXExprs; ++I)
3481 Consumer.addKeywordResult(CXXExprs[I]);
3483 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3484 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3485 Consumer.addKeywordResult("this");
3487 if (SemaRef.getLangOptions().CPlusPlus0x) {
3488 Consumer.addKeywordResult("alignof");
3489 Consumer.addKeywordResult("nullptr");
3494 if (WantRemainingKeywords) {
3495 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3497 const char *CStmts[] = {
3498 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3499 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3500 for (unsigned I = 0; I != NumCStmts; ++I)
3501 Consumer.addKeywordResult(CStmts[I]);
3503 if (SemaRef.getLangOptions().CPlusPlus) {
3504 Consumer.addKeywordResult("catch");
3505 Consumer.addKeywordResult("try");
3508 if (S && S->getBreakParent())
3509 Consumer.addKeywordResult("break");
3511 if (S && S->getContinueParent())
3512 Consumer.addKeywordResult("continue");
3514 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3515 Consumer.addKeywordResult("case");
3516 Consumer.addKeywordResult("default");
3519 if (SemaRef.getLangOptions().CPlusPlus) {
3520 Consumer.addKeywordResult("namespace");
3521 Consumer.addKeywordResult("template");
3524 if (S && S->isClassScope()) {
3525 Consumer.addKeywordResult("explicit");
3526 Consumer.addKeywordResult("friend");
3527 Consumer.addKeywordResult("mutable");
3528 Consumer.addKeywordResult("private");
3529 Consumer.addKeywordResult("protected");
3530 Consumer.addKeywordResult("public");
3531 Consumer.addKeywordResult("virtual");
3535 if (SemaRef.getLangOptions().CPlusPlus) {
3536 Consumer.addKeywordResult("using");
3538 if (SemaRef.getLangOptions().CPlusPlus0x)
3539 Consumer.addKeywordResult("static_assert");
3544 /// \brief Try to "correct" a typo in the source code by finding
3545 /// visible declarations whose names are similar to the name that was
3546 /// present in the source code.
3548 /// \param TypoName the \c DeclarationNameInfo structure that contains
3549 /// the name that was present in the source code along with its location.
3551 /// \param LookupKind the name-lookup criteria used to search for the name.
3553 /// \param S the scope in which name lookup occurs.
3555 /// \param SS the nested-name-specifier that precedes the name we're
3556 /// looking for, if present.
3558 /// \param MemberContext if non-NULL, the context in which to look for
3559 /// a member access expression.
3561 /// \param EnteringContext whether we're entering the context described by
3562 /// the nested-name-specifier SS.
3564 /// \param CTC The context in which typo correction occurs, which impacts the
3565 /// set of keywords permitted.
3567 /// \param OPT when non-NULL, the search for visible declarations will
3568 /// also walk the protocols in the qualified interfaces of \p OPT.
3570 /// \returns a \c TypoCorrection containing the corrected name if the typo
3571 /// along with information such as the \c NamedDecl where the corrected name
3572 /// was declared, and any additional \c NestedNameSpecifier needed to access
3573 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3574 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3575 Sema::LookupNameKind LookupKind,
3576 Scope *S, CXXScopeSpec *SS,
3577 DeclContext *MemberContext,
3578 bool EnteringContext,
3579 CorrectTypoContext CTC,
3580 const ObjCObjectPointerType *OPT) {
3581 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
3582 return TypoCorrection();
3584 // We only attempt to correct typos for identifiers.
3585 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
3587 return TypoCorrection();
3589 // If the scope specifier itself was invalid, don't try to correct
3591 if (SS && SS->isInvalid())
3592 return TypoCorrection();
3594 // Never try to correct typos during template deduction or
3596 if (!ActiveTemplateInstantiations.empty())
3597 return TypoCorrection();
3599 NamespaceSpecifierSet Namespaces(Context, CurContext);
3601 TypoCorrectionConsumer Consumer(*this, Typo);
3603 // Perform name lookup to find visible, similarly-named entities.
3604 bool IsUnqualifiedLookup = false;
3605 if (MemberContext) {
3606 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
3608 // Look in qualified interfaces.
3610 for (ObjCObjectPointerType::qual_iterator
3611 I = OPT->qual_begin(), E = OPT->qual_end();
3613 LookupVisibleDecls(*I, LookupKind, Consumer);
3615 } else if (SS && SS->isSet()) {
3616 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
3618 return TypoCorrection();
3620 // Provide a stop gap for files that are just seriously broken. Trying
3621 // to correct all typos can turn into a HUGE performance penalty, causing
3622 // some files to take minutes to get rejected by the parser.
3623 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3624 return TypoCorrection();
3627 LookupVisibleDecls(DC, LookupKind, Consumer);
3629 IsUnqualifiedLookup = true;
3630 UnqualifiedTyposCorrectedMap::iterator Cached
3631 = UnqualifiedTyposCorrected.find(Typo);
3632 if (Cached == UnqualifiedTyposCorrected.end()) {
3633 // Provide a stop gap for files that are just seriously broken. Trying
3634 // to correct all typos can turn into a HUGE performance penalty, causing
3635 // some files to take minutes to get rejected by the parser.
3636 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3637 return TypoCorrection();
3639 // For unqualified lookup, look through all of the names that we have
3640 // seen in this translation unit.
3641 for (IdentifierTable::iterator I = Context.Idents.begin(),
3642 IEnd = Context.Idents.end();
3644 Consumer.FoundName(I->getKey());
3646 // Walk through identifiers in external identifier sources.
3647 if (IdentifierInfoLookup *External
3648 = Context.Idents.getExternalIdentifierLookup()) {
3649 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
3651 llvm::StringRef Name = Iter->Next();
3655 Consumer.FoundName(Name);
3659 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3660 // end up adding the keyword below.
3661 if (!Cached->second)
3662 return TypoCorrection();
3664 if (!Cached->second.isKeyword())
3665 Consumer.addCorrection(Cached->second);
3669 AddKeywordsToConsumer(*this, Consumer, S, CTC);
3671 // If we haven't found anything, we're done.
3672 if (Consumer.empty()) {
3673 // If this was an unqualified lookup, note that no correction was found.
3674 if (IsUnqualifiedLookup)
3675 (void)UnqualifiedTyposCorrected[Typo];
3677 return TypoCorrection();
3680 // Make sure that the user typed at least 3 characters for each correction
3681 // made. Otherwise, we don't even both looking at the results.
3682 unsigned ED = Consumer.getBestEditDistance();
3683 if (ED > 0 && Typo->getName().size() / ED < 3) {
3684 // If this was an unqualified lookup, note that no correction was found.
3685 if (IsUnqualifiedLookup)
3686 (void)UnqualifiedTyposCorrected[Typo];
3688 return TypoCorrection();
3691 // Build the NestedNameSpecifiers for the KnownNamespaces
3692 if (getLangOptions().CPlusPlus) {
3693 // Load any externally-known namespaces.
3694 if (ExternalSource && !LoadedExternalKnownNamespaces) {
3695 llvm::SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
3696 LoadedExternalKnownNamespaces = true;
3697 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3698 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3699 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3702 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3703 KNI = KnownNamespaces.begin(),
3704 KNIEnd = KnownNamespaces.end();
3705 KNI != KNIEnd; ++KNI)
3706 Namespaces.AddNamespace(KNI->first);
3709 // Weed out any names that could not be found by name lookup.
3710 llvm::SmallPtrSet<IdentifierInfo*, 16> QualifiedResults;
3711 LookupResult TmpRes(*this, TypoName, LookupKind);
3712 TmpRes.suppressDiagnostics();
3713 while (!Consumer.empty()) {
3714 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3715 unsigned ED = DI->first;
3716 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3717 IEnd = DI->second->end();
3718 I != IEnd; /* Increment in loop. */) {
3719 // If the item already has been looked up or is a keyword, keep it
3720 if (I->second.isResolved()) {
3725 // Perform name lookup on this name.
3726 IdentifierInfo *Name = I->second.getCorrectionAsIdentifierInfo();
3727 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3728 EnteringContext, CTC);
3730 switch (TmpRes.getResultKind()) {
3731 case LookupResult::NotFound:
3732 case LookupResult::NotFoundInCurrentInstantiation:
3733 QualifiedResults.insert(Name);
3734 // We didn't find this name in our scope, or didn't like what we found;
3737 TypoCorrectionConsumer::result_iterator Next = I;
3739 DI->second->erase(I);
3744 case LookupResult::Ambiguous:
3745 // We don't deal with ambiguities.
3746 return TypoCorrection();
3748 case LookupResult::Found:
3749 case LookupResult::FoundOverloaded:
3750 case LookupResult::FoundUnresolvedValue:
3751 I->second.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3752 // FIXME: This sets the CorrectionDecl to NULL for overloaded functions.
3753 // It would be nice to find the right one with overload resolution.
3759 if (DI->second->empty())
3761 else if (!getLangOptions().CPlusPlus || QualifiedResults.empty() || !ED)
3762 // If there are results in the closest possible bucket, stop
3765 // Only perform the qualified lookups for C++
3766 if (getLangOptions().CPlusPlus) {
3767 TmpRes.suppressDiagnostics();
3768 for (llvm::SmallPtrSet<IdentifierInfo*,
3769 16>::iterator QRI = QualifiedResults.begin(),
3770 QRIEnd = QualifiedResults.end();
3771 QRI != QRIEnd; ++QRI) {
3772 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3773 NIEnd = Namespaces.end();
3774 NI != NIEnd; ++NI) {
3775 DeclContext *Ctx = NI->DeclCtx;
3776 unsigned QualifiedED = ED + NI->EditDistance;
3778 // Stop searching once the namespaces are too far away to create
3779 // acceptable corrections for this identifier (since the namespaces
3780 // are sorted in ascending order by edit distance)
3781 if (QualifiedED > Consumer.getMaxEditDistance()) break;
3784 TmpRes.setLookupName(*QRI);
3785 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3787 switch (TmpRes.getResultKind()) {
3788 case LookupResult::Found:
3789 case LookupResult::FoundOverloaded:
3790 case LookupResult::FoundUnresolvedValue:
3791 Consumer.addName((*QRI)->getName(), TmpRes.getAsSingle<NamedDecl>(),
3792 QualifiedED, NI->NameSpecifier);
3794 case LookupResult::NotFound:
3795 case LookupResult::NotFoundInCurrentInstantiation:
3796 case LookupResult::Ambiguous:
3803 QualifiedResults.clear();
3806 // No corrections remain...
3807 if (Consumer.empty()) return TypoCorrection();
3809 TypoResultsMap &BestResults = *Consumer.begin()->second;
3810 ED = Consumer.begin()->first;
3812 if (ED > 0 && Typo->getName().size() / ED < 3) {
3813 // If this was an unqualified lookup, note that no correction was found.
3814 if (IsUnqualifiedLookup)
3815 (void)UnqualifiedTyposCorrected[Typo];
3817 return TypoCorrection();
3820 // If we have multiple possible corrections, eliminate the ones where we
3821 // added namespace qualifiers to try to resolve the ambiguity (and to favor
3822 // corrections without additional namespace qualifiers)
3823 if (getLangOptions().CPlusPlus && BestResults.size() > 1) {
3824 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3825 for (TypoCorrectionConsumer::result_iterator I = DI->second->begin(),
3826 IEnd = DI->second->end();
3827 I != IEnd; /* Increment in loop. */) {
3828 if (I->second.getCorrectionSpecifier() != NULL) {
3829 TypoCorrectionConsumer::result_iterator Cur = I;
3831 DI->second->erase(Cur);
3836 // If only a single name remains, return that result.
3837 if (BestResults.size() == 1) {
3838 const llvm::StringMapEntry<TypoCorrection> &Correction = *(BestResults.begin());
3839 const TypoCorrection &Result = Correction.second;
3841 // Don't correct to a keyword that's the same as the typo; the keyword
3842 // wasn't actually in scope.
3843 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
3845 // Record the correction for unqualified lookup.
3846 if (IsUnqualifiedLookup)
3847 UnqualifiedTyposCorrected[Typo] = Result;
3851 else if (BestResults.size() > 1 && CTC == CTC_ObjCMessageReceiver
3852 && BestResults["super"].isKeyword()) {
3853 // Prefer 'super' when we're completing in a message-receiver
3856 // Don't correct to a keyword that's the same as the typo; the keyword
3857 // wasn't actually in scope.
3858 if (ED == 0) return TypoCorrection();
3860 // Record the correction for unqualified lookup.
3861 if (IsUnqualifiedLookup)
3862 UnqualifiedTyposCorrected[Typo] = BestResults["super"];
3864 return BestResults["super"];
3867 if (IsUnqualifiedLookup)
3868 (void)UnqualifiedTyposCorrected[Typo];
3870 return TypoCorrection();
3873 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
3874 if (CorrectionNameSpec) {
3875 std::string tmpBuffer;
3876 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
3877 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
3878 return PrefixOStream.str() + CorrectionName.getAsString();
3881 return CorrectionName.getAsString();