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/DeclLookups.h"
29 #include "clang/AST/DeclObjC.h"
30 #include "clang/AST/DeclTemplate.h"
31 #include "clang/AST/Expr.h"
32 #include "clang/AST/ExprCXX.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/LangOptions.h"
35 #include "llvm/ADT/SetVector.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/StringMap.h"
39 #include "llvm/ADT/TinyPtrVector.h"
40 #include "llvm/ADT/edit_distance.h"
41 #include "llvm/Support/ErrorHandling.h"
51 using namespace clang;
55 class UnqualUsingEntry {
56 const DeclContext *Nominated;
57 const DeclContext *CommonAncestor;
60 UnqualUsingEntry(const DeclContext *Nominated,
61 const DeclContext *CommonAncestor)
62 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
65 const DeclContext *getCommonAncestor() const {
66 return CommonAncestor;
69 const DeclContext *getNominatedNamespace() const {
73 // Sort by the pointer value of the common ancestor.
75 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
76 return L.getCommonAncestor() < R.getCommonAncestor();
79 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
80 return E.getCommonAncestor() < DC;
83 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
84 return DC < E.getCommonAncestor();
89 /// A collection of using directives, as used by C++ unqualified
91 class UnqualUsingDirectiveSet {
92 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
95 llvm::SmallPtrSet<DeclContext*, 8> visited;
98 UnqualUsingDirectiveSet() {}
100 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
101 // C++ [namespace.udir]p1:
102 // During unqualified name lookup, the names appear as if they
103 // were declared in the nearest enclosing namespace which contains
104 // both the using-directive and the nominated namespace.
105 DeclContext *InnermostFileDC
106 = static_cast<DeclContext*>(InnermostFileScope->getEntity());
107 assert(InnermostFileDC && InnermostFileDC->isFileContext());
109 for (; S; S = S->getParent()) {
110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
113 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
114 if (Ctx && Ctx->isFileContext()) {
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
117 Scope::udir_iterator I = S->using_directives_begin(),
118 End = S->using_directives_end();
119 for (; I != End; ++I)
120 visit(*I, InnermostFileDC);
125 // Visits a context and collect all of its using directives
126 // recursively. Treats all using directives as if they were
127 // declared in the context.
129 // A given context is only every visited once, so it is important
130 // that contexts be visited from the inside out in order to get
131 // the effective DCs right.
132 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
133 if (!visited.insert(DC))
136 addUsingDirectives(DC, EffectiveDC);
139 // Visits a using directive and collects all of its using
140 // directives recursively. Treats all using directives as if they
141 // were declared in the effective DC.
142 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
143 DeclContext *NS = UD->getNominatedNamespace();
144 if (!visited.insert(NS))
147 addUsingDirective(UD, EffectiveDC);
148 addUsingDirectives(NS, EffectiveDC);
151 // Adds all the using directives in a context (and those nominated
152 // by its using directives, transitively) as if they appeared in
153 // the given effective context.
154 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
155 SmallVector<DeclContext*,4> queue;
157 DeclContext::udir_iterator I, End;
158 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
159 UsingDirectiveDecl *UD = *I;
160 DeclContext *NS = UD->getNominatedNamespace();
161 if (visited.insert(NS)) {
162 addUsingDirective(UD, EffectiveDC);
175 // Add a using directive as if it had been declared in the given
176 // context. This helps implement C++ [namespace.udir]p3:
177 // The using-directive is transitive: if a scope contains a
178 // using-directive that nominates a second namespace that itself
179 // contains using-directives, the effect is as if the
180 // using-directives from the second namespace also appeared in
182 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
183 // Find the common ancestor between the effective context and
184 // the nominated namespace.
185 DeclContext *Common = UD->getNominatedNamespace();
186 while (!Common->Encloses(EffectiveDC))
187 Common = Common->getParent();
188 Common = Common->getPrimaryContext();
190 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
194 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
197 typedef ListTy::const_iterator const_iterator;
199 const_iterator begin() const { return list.begin(); }
200 const_iterator end() const { return list.end(); }
202 std::pair<const_iterator,const_iterator>
203 getNamespacesFor(DeclContext *DC) const {
204 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
205 UnqualUsingEntry::Comparator());
210 // Retrieve the set of identifier namespaces that correspond to a
211 // specific kind of name lookup.
212 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
214 bool Redeclaration) {
217 case Sema::LookupObjCImplicitSelfParam:
218 case Sema::LookupOrdinaryName:
219 case Sema::LookupRedeclarationWithLinkage:
220 IDNS = Decl::IDNS_Ordinary;
222 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
224 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup");
232 IDNS = Decl::IDNS_NonMemberOperator;
235 case Sema::LookupTagName:
237 IDNS = Decl::IDNS_Type;
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
247 IDNS = Decl::IDNS_Tag;
250 case Sema::LookupLabel:
251 IDNS = Decl::IDNS_Label;
254 case Sema::LookupMemberName:
255 IDNS = Decl::IDNS_Member;
257 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
260 case Sema::LookupNestedNameSpecifierName:
261 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
264 case Sema::LookupNamespaceName:
265 IDNS = Decl::IDNS_Namespace;
268 case Sema::LookupUsingDeclName:
269 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
270 | Decl::IDNS_Member | Decl::IDNS_Using;
273 case Sema::LookupObjCProtocolName:
274 IDNS = Decl::IDNS_ObjCProtocol;
277 case Sema::LookupAnyName:
278 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
279 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
286 void LookupResult::configure() {
287 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
288 isForRedeclaration());
290 // If we're looking for one of the allocation or deallocation
291 // operators, make sure that the implicitly-declared new and delete
292 // operators can be found.
293 if (!isForRedeclaration()) {
294 switch (NameInfo.getName().getCXXOverloadedOperator()) {
298 case OO_Array_Delete:
299 SemaRef.DeclareGlobalNewDelete();
308 void LookupResult::sanityImpl() const {
309 // Note that this function is never called by NDEBUG builds. See
310 // LookupResult::sanity().
311 assert(ResultKind != NotFound || Decls.size() == 0);
312 assert(ResultKind != Found || Decls.size() == 1);
313 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
314 (Decls.size() == 1 &&
315 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
316 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
317 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
318 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
319 Ambiguity == AmbiguousBaseSubobjectTypes)));
320 assert((Paths != NULL) == (ResultKind == Ambiguous &&
321 (Ambiguity == AmbiguousBaseSubobjectTypes ||
322 Ambiguity == AmbiguousBaseSubobjects)));
325 // Necessary because CXXBasePaths is not complete in Sema.h
326 void LookupResult::deletePaths(CXXBasePaths *Paths) {
330 static NamedDecl *getVisibleDecl(NamedDecl *D);
332 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
333 return getVisibleDecl(D);
336 /// Resolves the result kind of this lookup.
337 void LookupResult::resolveKind() {
338 unsigned N = Decls.size();
340 // Fast case: no possible ambiguity.
342 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
346 // If there's a single decl, we need to examine it to decide what
347 // kind of lookup this is.
349 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
350 if (isa<FunctionTemplateDecl>(D))
351 ResultKind = FoundOverloaded;
352 else if (isa<UnresolvedUsingValueDecl>(D))
353 ResultKind = FoundUnresolvedValue;
357 // Don't do any extra resolution if we've already resolved as ambiguous.
358 if (ResultKind == Ambiguous) return;
360 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
361 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
363 bool Ambiguous = false;
364 bool HasTag = false, HasFunction = false, HasNonFunction = false;
365 bool HasFunctionTemplate = false, HasUnresolved = false;
367 unsigned UniqueTagIndex = 0;
371 NamedDecl *D = Decls[I]->getUnderlyingDecl();
372 D = cast<NamedDecl>(D->getCanonicalDecl());
374 // Redeclarations of types via typedef can occur both within a scope
375 // and, through using declarations and directives, across scopes. There is
376 // no ambiguity if they all refer to the same type, so unique based on the
378 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
379 if (!TD->getDeclContext()->isRecord()) {
380 QualType T = SemaRef.Context.getTypeDeclType(TD);
381 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
382 // The type is not unique; pull something off the back and continue
384 Decls[I] = Decls[--N];
390 if (!Unique.insert(D)) {
391 // If it's not unique, pull something off the back (and
392 // continue at this index).
393 Decls[I] = Decls[--N];
397 // Otherwise, do some decl type analysis and then continue.
399 if (isa<UnresolvedUsingValueDecl>(D)) {
400 HasUnresolved = true;
401 } else if (isa<TagDecl>(D)) {
406 } else if (isa<FunctionTemplateDecl>(D)) {
408 HasFunctionTemplate = true;
409 } else if (isa<FunctionDecl>(D)) {
414 HasNonFunction = true;
419 // C++ [basic.scope.hiding]p2:
420 // A class name or enumeration name can be hidden by the name of
421 // an object, function, or enumerator declared in the same
422 // scope. If a class or enumeration name and an object, function,
423 // or enumerator are declared in the same scope (in any order)
424 // with the same name, the class or enumeration name is hidden
425 // wherever the object, function, or enumerator name is visible.
426 // But it's still an error if there are distinct tag types found,
427 // even if they're not visible. (ref?)
428 if (HideTags && HasTag && !Ambiguous &&
429 (HasFunction || HasNonFunction || HasUnresolved)) {
430 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
431 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
432 Decls[UniqueTagIndex] = Decls[--N];
439 if (HasNonFunction && (HasFunction || HasUnresolved))
443 setAmbiguous(LookupResult::AmbiguousReference);
444 else if (HasUnresolved)
445 ResultKind = LookupResult::FoundUnresolvedValue;
446 else if (N > 1 || HasFunctionTemplate)
447 ResultKind = LookupResult::FoundOverloaded;
449 ResultKind = LookupResult::Found;
452 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
453 CXXBasePaths::const_paths_iterator I, E;
454 DeclContext::lookup_iterator DI, DE;
455 for (I = P.begin(), E = P.end(); I != E; ++I)
456 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
460 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
461 Paths = new CXXBasePaths;
463 addDeclsFromBasePaths(*Paths);
465 setAmbiguous(AmbiguousBaseSubobjects);
468 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
469 Paths = new CXXBasePaths;
471 addDeclsFromBasePaths(*Paths);
473 setAmbiguous(AmbiguousBaseSubobjectTypes);
476 void LookupResult::print(raw_ostream &Out) {
477 Out << Decls.size() << " result(s)";
478 if (isAmbiguous()) Out << ", ambiguous";
479 if (Paths) Out << ", base paths present";
481 for (iterator I = begin(), E = end(); I != E; ++I) {
487 /// \brief Lookup a builtin function, when name lookup would otherwise
489 static bool LookupBuiltin(Sema &S, LookupResult &R) {
490 Sema::LookupNameKind NameKind = R.getLookupKind();
492 // If we didn't find a use of this identifier, and if the identifier
493 // corresponds to a compiler builtin, create the decl object for the builtin
494 // now, injecting it into translation unit scope, and return it.
495 if (NameKind == Sema::LookupOrdinaryName ||
496 NameKind == Sema::LookupRedeclarationWithLinkage) {
497 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
499 // If this is a builtin on this (or all) targets, create the decl.
500 if (unsigned BuiltinID = II->getBuiltinID()) {
501 // In C++, we don't have any predefined library functions like
502 // 'malloc'. Instead, we'll just error.
503 if (S.getLangOpts().CPlusPlus &&
504 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
507 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
508 BuiltinID, S.TUScope,
509 R.isForRedeclaration(),
515 if (R.isForRedeclaration()) {
516 // If we're redeclaring this function anyway, forget that
517 // this was a builtin at all.
518 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
529 /// \brief Determine whether we can declare a special member function within
530 /// the class at this point.
531 static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
532 const CXXRecordDecl *Class) {
533 // We need to have a definition for the class.
534 if (!Class->getDefinition() || Class->isDependentContext())
537 // We can't be in the middle of defining the class.
538 if (const RecordType *RecordTy
539 = Context.getTypeDeclType(Class)->getAs<RecordType>())
540 return !RecordTy->isBeingDefined();
545 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
546 if (!CanDeclareSpecialMemberFunction(Context, Class))
549 // If the default constructor has not yet been declared, do so now.
550 if (Class->needsImplicitDefaultConstructor())
551 DeclareImplicitDefaultConstructor(Class);
553 // If the copy constructor has not yet been declared, do so now.
554 if (!Class->hasDeclaredCopyConstructor())
555 DeclareImplicitCopyConstructor(Class);
557 // If the copy assignment operator has not yet been declared, do so now.
558 if (!Class->hasDeclaredCopyAssignment())
559 DeclareImplicitCopyAssignment(Class);
561 if (getLangOpts().CPlusPlus0x) {
562 // If the move constructor has not yet been declared, do so now.
563 if (Class->needsImplicitMoveConstructor())
564 DeclareImplicitMoveConstructor(Class); // might not actually do it
566 // If the move assignment operator has not yet been declared, do so now.
567 if (Class->needsImplicitMoveAssignment())
568 DeclareImplicitMoveAssignment(Class); // might not actually do it
571 // If the destructor has not yet been declared, do so now.
572 if (!Class->hasDeclaredDestructor())
573 DeclareImplicitDestructor(Class);
576 /// \brief Determine whether this is the name of an implicitly-declared
577 /// special member function.
578 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
579 switch (Name.getNameKind()) {
580 case DeclarationName::CXXConstructorName:
581 case DeclarationName::CXXDestructorName:
584 case DeclarationName::CXXOperatorName:
585 return Name.getCXXOverloadedOperator() == OO_Equal;
594 /// \brief If there are any implicit member functions with the given name
595 /// that need to be declared in the given declaration context, do so.
596 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
597 DeclarationName Name,
598 const DeclContext *DC) {
602 switch (Name.getNameKind()) {
603 case DeclarationName::CXXConstructorName:
604 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
605 if (Record->getDefinition() &&
606 CanDeclareSpecialMemberFunction(S.Context, Record)) {
607 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
608 if (Record->needsImplicitDefaultConstructor())
609 S.DeclareImplicitDefaultConstructor(Class);
610 if (!Record->hasDeclaredCopyConstructor())
611 S.DeclareImplicitCopyConstructor(Class);
612 if (S.getLangOpts().CPlusPlus0x &&
613 Record->needsImplicitMoveConstructor())
614 S.DeclareImplicitMoveConstructor(Class);
618 case DeclarationName::CXXDestructorName:
619 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
620 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
621 CanDeclareSpecialMemberFunction(S.Context, Record))
622 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
625 case DeclarationName::CXXOperatorName:
626 if (Name.getCXXOverloadedOperator() != OO_Equal)
629 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
630 if (Record->getDefinition() &&
631 CanDeclareSpecialMemberFunction(S.Context, Record)) {
632 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
633 if (!Record->hasDeclaredCopyAssignment())
634 S.DeclareImplicitCopyAssignment(Class);
635 if (S.getLangOpts().CPlusPlus0x &&
636 Record->needsImplicitMoveAssignment())
637 S.DeclareImplicitMoveAssignment(Class);
647 // Adds all qualifying matches for a name within a decl context to the
648 // given lookup result. Returns true if any matches were found.
649 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
652 // Lazily declare C++ special member functions.
653 if (S.getLangOpts().CPlusPlus)
654 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
656 // Perform lookup into this declaration context.
657 DeclContext::lookup_const_iterator I, E;
658 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
660 if ((D = R.getAcceptableDecl(D))) {
666 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
669 if (R.getLookupName().getNameKind()
670 != DeclarationName::CXXConversionFunctionName ||
671 R.getLookupName().getCXXNameType()->isDependentType() ||
672 !isa<CXXRecordDecl>(DC))
676 // A specialization of a conversion function template is not found by
677 // name lookup. Instead, any conversion function templates visible in the
678 // context of the use are considered. [...]
679 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
680 if (!Record->isCompleteDefinition())
683 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
684 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
685 UEnd = Unresolved->end(); U != UEnd; ++U) {
686 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
690 // When we're performing lookup for the purposes of redeclaration, just
691 // add the conversion function template. When we deduce template
692 // arguments for specializations, we'll end up unifying the return
693 // type of the new declaration with the type of the function template.
694 if (R.isForRedeclaration()) {
695 R.addDecl(ConvTemplate);
701 // [...] For each such operator, if argument deduction succeeds
702 // (14.9.2.3), the resulting specialization is used as if found by
705 // When referencing a conversion function for any purpose other than
706 // a redeclaration (such that we'll be building an expression with the
707 // result), perform template argument deduction and place the
708 // specialization into the result set. We do this to avoid forcing all
709 // callers to perform special deduction for conversion functions.
710 TemplateDeductionInfo Info(R.getNameLoc());
711 FunctionDecl *Specialization = 0;
713 const FunctionProtoType *ConvProto
714 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
715 assert(ConvProto && "Nonsensical conversion function template type");
717 // Compute the type of the function that we would expect the conversion
718 // function to have, if it were to match the name given.
719 // FIXME: Calling convention!
720 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
721 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
722 EPI.ExceptionSpecType = EST_None;
723 EPI.NumExceptions = 0;
724 QualType ExpectedType
725 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
728 // Perform template argument deduction against the type that we would
729 // expect the function to have.
730 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
731 Specialization, Info)
732 == Sema::TDK_Success) {
733 R.addDecl(Specialization);
741 // Performs C++ unqualified lookup into the given file context.
743 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
744 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
746 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
748 // Perform direct name lookup into the LookupCtx.
749 bool Found = LookupDirect(S, R, NS);
751 // Perform direct name lookup into the namespaces nominated by the
752 // using directives whose common ancestor is this namespace.
753 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
754 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
756 for (; UI != UEnd; ++UI)
757 if (LookupDirect(S, R, UI->getNominatedNamespace()))
765 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
766 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
767 return Ctx->isFileContext();
771 // Find the next outer declaration context from this scope. This
772 // routine actually returns the semantic outer context, which may
773 // differ from the lexical context (encoded directly in the Scope
774 // stack) when we are parsing a member of a class template. In this
775 // case, the second element of the pair will be true, to indicate that
776 // name lookup should continue searching in this semantic context when
777 // it leaves the current template parameter scope.
778 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
779 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
780 DeclContext *Lexical = 0;
781 for (Scope *OuterS = S->getParent(); OuterS;
782 OuterS = OuterS->getParent()) {
783 if (OuterS->getEntity()) {
784 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
789 // C++ [temp.local]p8:
790 // In the definition of a member of a class template that appears
791 // outside of the namespace containing the class template
792 // definition, the name of a template-parameter hides the name of
793 // a member of this namespace.
800 // template<class T> class B {
805 // template<class C> void N::B<C>::f(C) {
806 // C b; // C is the template parameter, not N::C
809 // In this example, the lexical context we return is the
810 // TranslationUnit, while the semantic context is the namespace N.
811 if (!Lexical || !DC || !S->getParent() ||
812 !S->getParent()->isTemplateParamScope())
813 return std::make_pair(Lexical, false);
815 // Find the outermost template parameter scope.
816 // For the example, this is the scope for the template parameters of
817 // template<class C>.
818 Scope *OutermostTemplateScope = S->getParent();
819 while (OutermostTemplateScope->getParent() &&
820 OutermostTemplateScope->getParent()->isTemplateParamScope())
821 OutermostTemplateScope = OutermostTemplateScope->getParent();
823 // Find the namespace context in which the original scope occurs. In
824 // the example, this is namespace N.
825 DeclContext *Semantic = DC;
826 while (!Semantic->isFileContext())
827 Semantic = Semantic->getParent();
829 // Find the declaration context just outside of the template
830 // parameter scope. This is the context in which the template is
831 // being lexically declaration (a namespace context). In the
832 // example, this is the global scope.
833 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
834 Lexical->Encloses(Semantic))
835 return std::make_pair(Semantic, true);
837 return std::make_pair(Lexical, false);
840 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
841 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
843 DeclarationName Name = R.getLookupName();
845 // If this is the name of an implicitly-declared special member function,
846 // go through the scope stack to implicitly declare
847 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
848 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
849 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
850 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
853 // Implicitly declare member functions with the name we're looking for, if in
854 // fact we are in a scope where it matters.
857 IdentifierResolver::iterator
858 I = IdResolver.begin(Name),
859 IEnd = IdResolver.end();
861 // First we lookup local scope.
862 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
863 // ...During unqualified name lookup (3.4.1), the names appear as if
864 // they were declared in the nearest enclosing namespace which contains
865 // both the using-directive and the nominated namespace.
866 // [Note: in this context, "contains" means "contains directly or
870 // namespace A { int i; }
874 // using namespace A;
875 // ++i; // finds local 'i', A::i appears at global scope
879 DeclContext *OutsideOfTemplateParamDC = 0;
880 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
881 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
883 // Check whether the IdResolver has anything in this scope.
885 for (; I != IEnd && S->isDeclScope(*I); ++I) {
886 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
893 if (S->isClassScope())
894 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
895 R.setNamingClass(Record);
899 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
900 S->getParent() && !S->getParent()->isTemplateParamScope()) {
901 // We've just searched the last template parameter scope and
902 // found nothing, so look into the contexts between the
903 // lexical and semantic declaration contexts returned by
904 // findOuterContext(). This implements the name lookup behavior
905 // of C++ [temp.local]p8.
906 Ctx = OutsideOfTemplateParamDC;
907 OutsideOfTemplateParamDC = 0;
911 DeclContext *OuterCtx;
912 bool SearchAfterTemplateScope;
913 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
914 if (SearchAfterTemplateScope)
915 OutsideOfTemplateParamDC = OuterCtx;
917 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
918 // We do not directly look into transparent contexts, since
919 // those entities will be found in the nearest enclosing
920 // non-transparent context.
921 if (Ctx->isTransparentContext())
924 // We do not look directly into function or method contexts,
925 // since all of the local variables and parameters of the
926 // function/method are present within the Scope.
927 if (Ctx->isFunctionOrMethod()) {
928 // If we have an Objective-C instance method, look for ivars
929 // in the corresponding interface.
930 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
931 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
932 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
933 ObjCInterfaceDecl *ClassDeclared;
934 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
935 Name.getAsIdentifierInfo(),
937 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
949 // Perform qualified name lookup into this context.
950 // FIXME: In some cases, we know that every name that could be found by
951 // this qualified name lookup will also be on the identifier chain. For
952 // example, inside a class without any base classes, we never need to
953 // perform qualified lookup because all of the members are on top of the
955 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
961 // Stop if we ran out of scopes.
962 // FIXME: This really, really shouldn't be happening.
963 if (!S) return false;
965 // If we are looking for members, no need to look into global/namespace scope.
966 if (R.getLookupKind() == LookupMemberName)
969 // Collect UsingDirectiveDecls in all scopes, and recursively all
970 // nominated namespaces by those using-directives.
972 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
973 // don't build it for each lookup!
975 UnqualUsingDirectiveSet UDirs;
976 UDirs.visitScopeChain(Initial, S);
979 // Lookup namespace scope, and global scope.
980 // Unqualified name lookup in C++ requires looking into scopes
981 // that aren't strictly lexical, and therefore we walk through the
982 // context as well as walking through the scopes.
984 for (; S; S = S->getParent()) {
985 // Check whether the IdResolver has anything in this scope.
987 for (; I != IEnd && S->isDeclScope(*I); ++I) {
988 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
989 // We found something. Look for anything else in our scope
990 // with this same name and in an acceptable identifier
991 // namespace, so that we can construct an overload set if we
998 if (Found && S->isTemplateParamScope()) {
1003 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1004 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1005 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1006 // We've just searched the last template parameter scope and
1007 // found nothing, so look into the contexts between the
1008 // lexical and semantic declaration contexts returned by
1009 // findOuterContext(). This implements the name lookup behavior
1010 // of C++ [temp.local]p8.
1011 Ctx = OutsideOfTemplateParamDC;
1012 OutsideOfTemplateParamDC = 0;
1016 DeclContext *OuterCtx;
1017 bool SearchAfterTemplateScope;
1018 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1019 if (SearchAfterTemplateScope)
1020 OutsideOfTemplateParamDC = OuterCtx;
1022 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1023 // We do not directly look into transparent contexts, since
1024 // those entities will be found in the nearest enclosing
1025 // non-transparent context.
1026 if (Ctx->isTransparentContext())
1029 // If we have a context, and it's not a context stashed in the
1030 // template parameter scope for an out-of-line definition, also
1031 // look into that context.
1032 if (!(Found && S && S->isTemplateParamScope())) {
1033 assert(Ctx->isFileContext() &&
1034 "We should have been looking only at file context here already.");
1036 // Look into context considering using-directives.
1037 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1046 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1051 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1058 /// \brief Retrieve the visible declaration corresponding to D, if any.
1060 /// This routine determines whether the declaration D is visible in the current
1061 /// module, with the current imports. If not, it checks whether any
1062 /// redeclaration of D is visible, and if so, returns that declaration.
1064 /// \returns D, or a visible previous declaration of D, whichever is more recent
1065 /// and visible. If no declaration of D is visible, returns null.
1066 static NamedDecl *getVisibleDecl(NamedDecl *D) {
1067 if (LookupResult::isVisible(D))
1070 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1071 RD != RDEnd; ++RD) {
1072 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1073 if (LookupResult::isVisible(ND))
1081 /// @brief Perform unqualified name lookup starting from a given
1084 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1085 /// used to find names within the current scope. For example, 'x' in
1089 /// return x; // unqualified name look finds 'x' in the global scope
1093 /// Different lookup criteria can find different names. For example, a
1094 /// particular scope can have both a struct and a function of the same
1095 /// name, and each can be found by certain lookup criteria. For more
1096 /// information about lookup criteria, see the documentation for the
1097 /// class LookupCriteria.
1099 /// @param S The scope from which unqualified name lookup will
1100 /// begin. If the lookup criteria permits, name lookup may also search
1101 /// in the parent scopes.
1103 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1104 /// look up and the lookup kind), and is updated with the results of lookup
1105 /// including zero or more declarations and possibly additional information
1106 /// used to diagnose ambiguities.
1108 /// @returns \c true if lookup succeeded and false otherwise.
1109 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1110 DeclarationName Name = R.getLookupName();
1111 if (!Name) return false;
1113 LookupNameKind NameKind = R.getLookupKind();
1115 if (!getLangOpts().CPlusPlus) {
1116 // Unqualified name lookup in C/Objective-C is purely lexical, so
1117 // search in the declarations attached to the name.
1118 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1119 // Find the nearest non-transparent declaration scope.
1120 while (!(S->getFlags() & Scope::DeclScope) ||
1122 static_cast<DeclContext *>(S->getEntity())
1123 ->isTransparentContext()))
1127 unsigned IDNS = R.getIdentifierNamespace();
1129 // Scan up the scope chain looking for a decl that matches this
1130 // identifier that is in the appropriate namespace. This search
1131 // should not take long, as shadowing of names is uncommon, and
1132 // deep shadowing is extremely uncommon.
1133 bool LeftStartingScope = false;
1135 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1136 IEnd = IdResolver.end();
1138 if ((*I)->isInIdentifierNamespace(IDNS)) {
1139 if (NameKind == LookupRedeclarationWithLinkage) {
1140 // Determine whether this (or a previous) declaration is
1142 if (!LeftStartingScope && !S->isDeclScope(*I))
1143 LeftStartingScope = true;
1145 // If we found something outside of our starting scope that
1146 // does not have linkage, skip it.
1147 if (LeftStartingScope && !((*I)->hasLinkage()))
1150 else if (NameKind == LookupObjCImplicitSelfParam &&
1151 !isa<ImplicitParamDecl>(*I))
1154 // If this declaration is module-private and it came from an AST
1155 // file, we can't see it.
1156 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
1162 // Check whether there are any other declarations with the same name
1163 // and in the same scope.
1165 // Find the scope in which this declaration was declared (if it
1166 // actually exists in a Scope).
1167 while (S && !S->isDeclScope(D))
1170 // If the scope containing the declaration is the translation unit,
1171 // then we'll need to perform our checks based on the matching
1172 // DeclContexts rather than matching scopes.
1173 if (S && isNamespaceOrTranslationUnitScope(S))
1176 // Compute the DeclContext, if we need it.
1177 DeclContext *DC = 0;
1179 DC = (*I)->getDeclContext()->getRedeclContext();
1181 IdentifierResolver::iterator LastI = I;
1182 for (++LastI; LastI != IEnd; ++LastI) {
1184 // Match based on scope.
1185 if (!S->isDeclScope(*LastI))
1188 // Match based on DeclContext.
1190 = (*LastI)->getDeclContext()->getRedeclContext();
1191 if (!LastDC->Equals(DC))
1195 // If the declaration isn't in the right namespace, skip it.
1196 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1199 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
1209 // Perform C++ unqualified name lookup.
1210 if (CppLookupName(R, S))
1214 // If we didn't find a use of this identifier, and if the identifier
1215 // corresponds to a compiler builtin, create the decl object for the builtin
1216 // now, injecting it into translation unit scope, and return it.
1217 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1220 // If we didn't find a use of this identifier, the ExternalSource
1221 // may be able to handle the situation.
1222 // Note: some lookup failures are expected!
1223 // See e.g. R.isForRedeclaration().
1224 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1227 /// @brief Perform qualified name lookup in the namespaces nominated by
1228 /// using directives by the given context.
1230 /// C++98 [namespace.qual]p2:
1231 /// Given X::m (where X is a user-declared namespace), or given \::m
1232 /// (where X is the global namespace), let S be the set of all
1233 /// declarations of m in X and in the transitive closure of all
1234 /// namespaces nominated by using-directives in X and its used
1235 /// namespaces, except that using-directives are ignored in any
1236 /// namespace, including X, directly containing one or more
1237 /// declarations of m. No namespace is searched more than once in
1238 /// the lookup of a name. If S is the empty set, the program is
1239 /// ill-formed. Otherwise, if S has exactly one member, or if the
1240 /// context of the reference is a using-declaration
1241 /// (namespace.udecl), S is the required set of declarations of
1242 /// m. Otherwise if the use of m is not one that allows a unique
1243 /// declaration to be chosen from S, the program is ill-formed.
1245 /// C++98 [namespace.qual]p5:
1246 /// During the lookup of a qualified namespace member name, if the
1247 /// lookup finds more than one declaration of the member, and if one
1248 /// declaration introduces a class name or enumeration name and the
1249 /// other declarations either introduce the same object, the same
1250 /// enumerator or a set of functions, the non-type name hides the
1251 /// class or enumeration name if and only if the declarations are
1252 /// from the same namespace; otherwise (the declarations are from
1253 /// different namespaces), the program is ill-formed.
1254 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1255 DeclContext *StartDC) {
1256 assert(StartDC->isFileContext() && "start context is not a file context");
1258 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1259 DeclContext::udir_iterator E = StartDC->using_directives_end();
1261 if (I == E) return false;
1263 // We have at least added all these contexts to the queue.
1264 llvm::SmallPtrSet<DeclContext*, 8> Visited;
1265 Visited.insert(StartDC);
1267 // We have not yet looked into these namespaces, much less added
1268 // their "using-children" to the queue.
1269 SmallVector<NamespaceDecl*, 8> Queue;
1271 // We have already looked into the initial namespace; seed the queue
1272 // with its using-children.
1273 for (; I != E; ++I) {
1274 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1275 if (Visited.insert(ND))
1276 Queue.push_back(ND);
1279 // The easiest way to implement the restriction in [namespace.qual]p5
1280 // is to check whether any of the individual results found a tag
1281 // and, if so, to declare an ambiguity if the final result is not
1283 bool FoundTag = false;
1284 bool FoundNonTag = false;
1286 LookupResult LocalR(LookupResult::Temporary, R);
1289 while (!Queue.empty()) {
1290 NamespaceDecl *ND = Queue.back();
1293 // We go through some convolutions here to avoid copying results
1294 // between LookupResults.
1295 bool UseLocal = !R.empty();
1296 LookupResult &DirectR = UseLocal ? LocalR : R;
1297 bool FoundDirect = LookupDirect(S, DirectR, ND);
1300 // First do any local hiding.
1301 DirectR.resolveKind();
1303 // If the local result is a tag, remember that.
1304 if (DirectR.isSingleTagDecl())
1309 // Append the local results to the total results if necessary.
1311 R.addAllDecls(LocalR);
1316 // If we find names in this namespace, ignore its using directives.
1322 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1323 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1324 if (Visited.insert(Nom))
1325 Queue.push_back(Nom);
1330 if (FoundTag && FoundNonTag)
1331 R.setAmbiguousQualifiedTagHiding();
1339 /// \brief Callback that looks for any member of a class with the given name.
1340 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1343 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1345 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1346 Path.Decls = BaseRecord->lookup(N);
1347 return Path.Decls.first != Path.Decls.second;
1350 /// \brief Determine whether the given set of member declarations contains only
1351 /// static members, nested types, and enumerators.
1352 template<typename InputIterator>
1353 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1354 Decl *D = (*First)->getUnderlyingDecl();
1355 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1358 if (isa<CXXMethodDecl>(D)) {
1359 // Determine whether all of the methods are static.
1360 bool AllMethodsAreStatic = true;
1361 for(; First != Last; ++First) {
1362 D = (*First)->getUnderlyingDecl();
1364 if (!isa<CXXMethodDecl>(D)) {
1365 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1369 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1370 AllMethodsAreStatic = false;
1375 if (AllMethodsAreStatic)
1382 /// \brief Perform qualified name lookup into a given context.
1384 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1385 /// names when the context of those names is explicit specified, e.g.,
1386 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1388 /// Different lookup criteria can find different names. For example, a
1389 /// particular scope can have both a struct and a function of the same
1390 /// name, and each can be found by certain lookup criteria. For more
1391 /// information about lookup criteria, see the documentation for the
1392 /// class LookupCriteria.
1394 /// \param R captures both the lookup criteria and any lookup results found.
1396 /// \param LookupCtx The context in which qualified name lookup will
1397 /// search. If the lookup criteria permits, name lookup may also search
1398 /// in the parent contexts or (for C++ classes) base classes.
1400 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1401 /// occurs as part of unqualified name lookup.
1403 /// \returns true if lookup succeeded, false if it failed.
1404 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1405 bool InUnqualifiedLookup) {
1406 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1408 if (!R.getLookupName())
1411 // Make sure that the declaration context is complete.
1412 assert((!isa<TagDecl>(LookupCtx) ||
1413 LookupCtx->isDependentContext() ||
1414 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
1415 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
1416 "Declaration context must already be complete!");
1418 // Perform qualified name lookup into the LookupCtx.
1419 if (LookupDirect(*this, R, LookupCtx)) {
1421 if (isa<CXXRecordDecl>(LookupCtx))
1422 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1426 // Don't descend into implied contexts for redeclarations.
1427 // C++98 [namespace.qual]p6:
1428 // In a declaration for a namespace member in which the
1429 // declarator-id is a qualified-id, given that the qualified-id
1430 // for the namespace member has the form
1431 // nested-name-specifier unqualified-id
1432 // the unqualified-id shall name a member of the namespace
1433 // designated by the nested-name-specifier.
1434 // See also [class.mfct]p5 and [class.static.data]p2.
1435 if (R.isForRedeclaration())
1438 // If this is a namespace, look it up in the implied namespaces.
1439 if (LookupCtx->isFileContext())
1440 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1442 // If this isn't a C++ class, we aren't allowed to look into base
1443 // classes, we're done.
1444 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1445 if (!LookupRec || !LookupRec->getDefinition())
1448 // If we're performing qualified name lookup into a dependent class,
1449 // then we are actually looking into a current instantiation. If we have any
1450 // dependent base classes, then we either have to delay lookup until
1451 // template instantiation time (at which point all bases will be available)
1452 // or we have to fail.
1453 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1454 LookupRec->hasAnyDependentBases()) {
1455 R.setNotFoundInCurrentInstantiation();
1459 // Perform lookup into our base classes.
1461 Paths.setOrigin(LookupRec);
1463 // Look for this member in our base classes
1464 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1465 switch (R.getLookupKind()) {
1466 case LookupObjCImplicitSelfParam:
1467 case LookupOrdinaryName:
1468 case LookupMemberName:
1469 case LookupRedeclarationWithLinkage:
1470 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1474 BaseCallback = &CXXRecordDecl::FindTagMember;
1478 BaseCallback = &LookupAnyMember;
1481 case LookupUsingDeclName:
1482 // This lookup is for redeclarations only.
1484 case LookupOperatorName:
1485 case LookupNamespaceName:
1486 case LookupObjCProtocolName:
1488 // These lookups will never find a member in a C++ class (or base class).
1491 case LookupNestedNameSpecifierName:
1492 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1496 if (!LookupRec->lookupInBases(BaseCallback,
1497 R.getLookupName().getAsOpaquePtr(), Paths))
1500 R.setNamingClass(LookupRec);
1502 // C++ [class.member.lookup]p2:
1503 // [...] If the resulting set of declarations are not all from
1504 // sub-objects of the same type, or the set has a nonstatic member
1505 // and includes members from distinct sub-objects, there is an
1506 // ambiguity and the program is ill-formed. Otherwise that set is
1507 // the result of the lookup.
1508 QualType SubobjectType;
1509 int SubobjectNumber = 0;
1510 AccessSpecifier SubobjectAccess = AS_none;
1512 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1513 Path != PathEnd; ++Path) {
1514 const CXXBasePathElement &PathElement = Path->back();
1516 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1517 // across all paths.
1518 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1520 // Determine whether we're looking at a distinct sub-object or not.
1521 if (SubobjectType.isNull()) {
1522 // This is the first subobject we've looked at. Record its type.
1523 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1524 SubobjectNumber = PathElement.SubobjectNumber;
1529 != Context.getCanonicalType(PathElement.Base->getType())) {
1530 // We found members of the given name in two subobjects of
1531 // different types. If the declaration sets aren't the same, this
1532 // this lookup is ambiguous.
1533 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1534 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1535 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1536 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1538 while (FirstD != FirstPath->Decls.second &&
1539 CurrentD != Path->Decls.second) {
1540 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1541 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1548 if (FirstD == FirstPath->Decls.second &&
1549 CurrentD == Path->Decls.second)
1553 R.setAmbiguousBaseSubobjectTypes(Paths);
1557 if (SubobjectNumber != PathElement.SubobjectNumber) {
1558 // We have a different subobject of the same type.
1560 // C++ [class.member.lookup]p5:
1561 // A static member, a nested type or an enumerator defined in
1562 // a base class T can unambiguously be found even if an object
1563 // has more than one base class subobject of type T.
1564 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
1567 // We have found a nonstatic member name in multiple, distinct
1568 // subobjects. Name lookup is ambiguous.
1569 R.setAmbiguousBaseSubobjects(Paths);
1574 // Lookup in a base class succeeded; return these results.
1576 DeclContext::lookup_iterator I, E;
1577 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1579 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1587 /// @brief Performs name lookup for a name that was parsed in the
1588 /// source code, and may contain a C++ scope specifier.
1590 /// This routine is a convenience routine meant to be called from
1591 /// contexts that receive a name and an optional C++ scope specifier
1592 /// (e.g., "N::M::x"). It will then perform either qualified or
1593 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1594 /// respectively) on the given name and return those results.
1596 /// @param S The scope from which unqualified name lookup will
1599 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1601 /// @param EnteringContext Indicates whether we are going to enter the
1602 /// context of the scope-specifier SS (if present).
1604 /// @returns True if any decls were found (but possibly ambiguous)
1605 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1606 bool AllowBuiltinCreation, bool EnteringContext) {
1607 if (SS && SS->isInvalid()) {
1608 // When the scope specifier is invalid, don't even look for
1613 if (SS && SS->isSet()) {
1614 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1615 // We have resolved the scope specifier to a particular declaration
1616 // contex, and will perform name lookup in that context.
1617 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1620 R.setContextRange(SS->getRange());
1621 return LookupQualifiedName(R, DC);
1624 // We could not resolve the scope specified to a specific declaration
1625 // context, which means that SS refers to an unknown specialization.
1626 // Name lookup can't find anything in this case.
1627 R.setNotFoundInCurrentInstantiation();
1628 R.setContextRange(SS->getRange());
1632 // Perform unqualified name lookup starting in the given scope.
1633 return LookupName(R, S, AllowBuiltinCreation);
1637 /// \brief Produce a diagnostic describing the ambiguity that resulted
1638 /// from name lookup.
1640 /// \param Result The result of the ambiguous lookup to be diagnosed.
1643 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1644 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1646 DeclarationName Name = Result.getLookupName();
1647 SourceLocation NameLoc = Result.getNameLoc();
1648 SourceRange LookupRange = Result.getContextRange();
1650 switch (Result.getAmbiguityKind()) {
1651 case LookupResult::AmbiguousBaseSubobjects: {
1652 CXXBasePaths *Paths = Result.getBasePaths();
1653 QualType SubobjectType = Paths->front().back().Base->getType();
1654 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1655 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1658 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1659 while (isa<CXXMethodDecl>(*Found) &&
1660 cast<CXXMethodDecl>(*Found)->isStatic())
1663 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1668 case LookupResult::AmbiguousBaseSubobjectTypes: {
1669 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1670 << Name << LookupRange;
1672 CXXBasePaths *Paths = Result.getBasePaths();
1673 std::set<Decl *> DeclsPrinted;
1674 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1675 PathEnd = Paths->end();
1676 Path != PathEnd; ++Path) {
1677 Decl *D = *Path->Decls.first;
1678 if (DeclsPrinted.insert(D).second)
1679 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1685 case LookupResult::AmbiguousTagHiding: {
1686 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1688 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1690 LookupResult::iterator DI, DE = Result.end();
1691 for (DI = Result.begin(); DI != DE; ++DI)
1692 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1693 TagDecls.insert(TD);
1694 Diag(TD->getLocation(), diag::note_hidden_tag);
1697 for (DI = Result.begin(); DI != DE; ++DI)
1698 if (!isa<TagDecl>(*DI))
1699 Diag((*DI)->getLocation(), diag::note_hiding_object);
1701 // For recovery purposes, go ahead and implement the hiding.
1702 LookupResult::Filter F = Result.makeFilter();
1703 while (F.hasNext()) {
1704 if (TagDecls.count(F.next()))
1712 case LookupResult::AmbiguousReference: {
1713 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1715 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1716 for (; DI != DE; ++DI)
1717 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1723 llvm_unreachable("unknown ambiguity kind");
1727 struct AssociatedLookup {
1728 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
1729 Sema::AssociatedNamespaceSet &Namespaces,
1730 Sema::AssociatedClassSet &Classes)
1731 : S(S), Namespaces(Namespaces), Classes(Classes),
1732 InstantiationLoc(InstantiationLoc) {
1736 Sema::AssociatedNamespaceSet &Namespaces;
1737 Sema::AssociatedClassSet &Classes;
1738 SourceLocation InstantiationLoc;
1743 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1745 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1747 // Add the associated namespace for this class.
1749 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1750 // be a locally scoped record.
1752 // We skip out of inline namespaces. The innermost non-inline namespace
1753 // contains all names of all its nested inline namespaces anyway, so we can
1754 // replace the entire inline namespace tree with its root.
1755 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1756 Ctx->isInlineNamespace())
1757 Ctx = Ctx->getParent();
1759 if (Ctx->isFileContext())
1760 Namespaces.insert(Ctx->getPrimaryContext());
1763 // \brief Add the associated classes and namespaces for argument-dependent
1764 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1766 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1767 const TemplateArgument &Arg) {
1768 // C++ [basic.lookup.koenig]p2, last bullet:
1770 switch (Arg.getKind()) {
1771 case TemplateArgument::Null:
1774 case TemplateArgument::Type:
1775 // [...] the namespaces and classes associated with the types of the
1776 // template arguments provided for template type parameters (excluding
1777 // template template parameters)
1778 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1781 case TemplateArgument::Template:
1782 case TemplateArgument::TemplateExpansion: {
1783 // [...] the namespaces in which any template template arguments are
1784 // defined; and the classes in which any member templates used as
1785 // template template arguments are defined.
1786 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1787 if (ClassTemplateDecl *ClassTemplate
1788 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1789 DeclContext *Ctx = ClassTemplate->getDeclContext();
1790 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1791 Result.Classes.insert(EnclosingClass);
1792 // Add the associated namespace for this class.
1793 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1798 case TemplateArgument::Declaration:
1799 case TemplateArgument::Integral:
1800 case TemplateArgument::Expression:
1801 case TemplateArgument::NullPtr:
1802 // [Note: non-type template arguments do not contribute to the set of
1803 // associated namespaces. ]
1806 case TemplateArgument::Pack:
1807 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1808 PEnd = Arg.pack_end();
1810 addAssociatedClassesAndNamespaces(Result, *P);
1815 // \brief Add the associated classes and namespaces for
1816 // argument-dependent lookup with an argument of class type
1817 // (C++ [basic.lookup.koenig]p2).
1819 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1820 CXXRecordDecl *Class) {
1822 // Just silently ignore anything whose name is __va_list_tag.
1823 if (Class->getDeclName() == Result.S.VAListTagName)
1826 // C++ [basic.lookup.koenig]p2:
1828 // -- If T is a class type (including unions), its associated
1829 // classes are: the class itself; the class of which it is a
1830 // member, if any; and its direct and indirect base
1831 // classes. Its associated namespaces are the namespaces in
1832 // which its associated classes are defined.
1834 // Add the class of which it is a member, if any.
1835 DeclContext *Ctx = Class->getDeclContext();
1836 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1837 Result.Classes.insert(EnclosingClass);
1838 // Add the associated namespace for this class.
1839 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1841 // Add the class itself. If we've already seen this class, we don't
1842 // need to visit base classes.
1843 if (!Result.Classes.insert(Class))
1846 // -- If T is a template-id, its associated namespaces and classes are
1847 // the namespace in which the template is defined; for member
1848 // templates, the member template's class; the namespaces and classes
1849 // associated with the types of the template arguments provided for
1850 // template type parameters (excluding template template parameters); the
1851 // namespaces in which any template template arguments are defined; and
1852 // the classes in which any member templates used as template template
1853 // arguments are defined. [Note: non-type template arguments do not
1854 // contribute to the set of associated namespaces. ]
1855 if (ClassTemplateSpecializationDecl *Spec
1856 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1857 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1858 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1859 Result.Classes.insert(EnclosingClass);
1860 // Add the associated namespace for this class.
1861 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1863 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1864 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1865 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
1868 // Only recurse into base classes for complete types.
1869 if (!Class->hasDefinition()) {
1870 QualType type = Result.S.Context.getTypeDeclType(Class);
1871 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
1872 /*no diagnostic*/ 0))
1876 // Add direct and indirect base classes along with their associated
1878 SmallVector<CXXRecordDecl *, 32> Bases;
1879 Bases.push_back(Class);
1880 while (!Bases.empty()) {
1881 // Pop this class off the stack.
1882 Class = Bases.back();
1885 // Visit the base classes.
1886 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1887 BaseEnd = Class->bases_end();
1888 Base != BaseEnd; ++Base) {
1889 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1890 // In dependent contexts, we do ADL twice, and the first time around,
1891 // the base type might be a dependent TemplateSpecializationType, or a
1892 // TemplateTypeParmType. If that happens, simply ignore it.
1893 // FIXME: If we want to support export, we probably need to add the
1894 // namespace of the template in a TemplateSpecializationType, or even
1895 // the classes and namespaces of known non-dependent arguments.
1898 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1899 if (Result.Classes.insert(BaseDecl)) {
1900 // Find the associated namespace for this base class.
1901 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1902 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
1904 // Make sure we visit the bases of this base class.
1905 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1906 Bases.push_back(BaseDecl);
1912 // \brief Add the associated classes and namespaces for
1913 // argument-dependent lookup with an argument of type T
1914 // (C++ [basic.lookup.koenig]p2).
1916 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
1917 // C++ [basic.lookup.koenig]p2:
1919 // For each argument type T in the function call, there is a set
1920 // of zero or more associated namespaces and a set of zero or more
1921 // associated classes to be considered. The sets of namespaces and
1922 // classes is determined entirely by the types of the function
1923 // arguments (and the namespace of any template template
1924 // argument). Typedef names and using-declarations used to specify
1925 // the types do not contribute to this set. The sets of namespaces
1926 // and classes are determined in the following way:
1928 SmallVector<const Type *, 16> Queue;
1929 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1932 switch (T->getTypeClass()) {
1934 #define TYPE(Class, Base)
1935 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1936 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1937 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1938 #define ABSTRACT_TYPE(Class, Base)
1939 #include "clang/AST/TypeNodes.def"
1940 // T is canonical. We can also ignore dependent types because
1941 // we don't need to do ADL at the definition point, but if we
1942 // wanted to implement template export (or if we find some other
1943 // use for associated classes and namespaces...) this would be
1947 // -- If T is a pointer to U or an array of U, its associated
1948 // namespaces and classes are those associated with U.
1950 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1952 case Type::ConstantArray:
1953 case Type::IncompleteArray:
1954 case Type::VariableArray:
1955 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1958 // -- If T is a fundamental type, its associated sets of
1959 // namespaces and classes are both empty.
1963 // -- If T is a class type (including unions), its associated
1964 // classes are: the class itself; the class of which it is a
1965 // member, if any; and its direct and indirect base
1966 // classes. Its associated namespaces are the namespaces in
1967 // which its associated classes are defined.
1968 case Type::Record: {
1969 CXXRecordDecl *Class
1970 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
1971 addAssociatedClassesAndNamespaces(Result, Class);
1975 // -- If T is an enumeration type, its associated namespace is
1976 // the namespace in which it is defined. If it is class
1977 // member, its associated class is the member's class; else
1978 // it has no associated class.
1980 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
1982 DeclContext *Ctx = Enum->getDeclContext();
1983 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1984 Result.Classes.insert(EnclosingClass);
1986 // Add the associated namespace for this class.
1987 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1992 // -- If T is a function type, its associated namespaces and
1993 // classes are those associated with the function parameter
1994 // types and those associated with the return type.
1995 case Type::FunctionProto: {
1996 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1997 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1998 ArgEnd = Proto->arg_type_end();
1999 Arg != ArgEnd; ++Arg)
2000 Queue.push_back(Arg->getTypePtr());
2003 case Type::FunctionNoProto: {
2004 const FunctionType *FnType = cast<FunctionType>(T);
2005 T = FnType->getResultType().getTypePtr();
2009 // -- If T is a pointer to a member function of a class X, its
2010 // associated namespaces and classes are those associated
2011 // with the function parameter types and return type,
2012 // together with those associated with X.
2014 // -- If T is a pointer to a data member of class X, its
2015 // associated namespaces and classes are those associated
2016 // with the member type together with those associated with
2018 case Type::MemberPointer: {
2019 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2021 // Queue up the class type into which this points.
2022 Queue.push_back(MemberPtr->getClass());
2024 // And directly continue with the pointee type.
2025 T = MemberPtr->getPointeeType().getTypePtr();
2029 // As an extension, treat this like a normal pointer.
2030 case Type::BlockPointer:
2031 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2034 // References aren't covered by the standard, but that's such an
2035 // obvious defect that we cover them anyway.
2036 case Type::LValueReference:
2037 case Type::RValueReference:
2038 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2041 // These are fundamental types.
2043 case Type::ExtVector:
2047 // If T is an Objective-C object or interface type, or a pointer to an
2048 // object or interface type, the associated namespace is the global
2050 case Type::ObjCObject:
2051 case Type::ObjCInterface:
2052 case Type::ObjCObjectPointer:
2053 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2056 // Atomic types are just wrappers; use the associations of the
2059 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2063 if (Queue.empty()) break;
2069 /// \brief Find the associated classes and namespaces for
2070 /// argument-dependent lookup for a call with the given set of
2073 /// This routine computes the sets of associated classes and associated
2074 /// namespaces searched by argument-dependent lookup
2075 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
2077 Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2078 llvm::ArrayRef<Expr *> Args,
2079 AssociatedNamespaceSet &AssociatedNamespaces,
2080 AssociatedClassSet &AssociatedClasses) {
2081 AssociatedNamespaces.clear();
2082 AssociatedClasses.clear();
2084 AssociatedLookup Result(*this, InstantiationLoc,
2085 AssociatedNamespaces, AssociatedClasses);
2087 // C++ [basic.lookup.koenig]p2:
2088 // For each argument type T in the function call, there is a set
2089 // of zero or more associated namespaces and a set of zero or more
2090 // associated classes to be considered. The sets of namespaces and
2091 // classes is determined entirely by the types of the function
2092 // arguments (and the namespace of any template template
2094 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2095 Expr *Arg = Args[ArgIdx];
2097 if (Arg->getType() != Context.OverloadTy) {
2098 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2102 // [...] In addition, if the argument is the name or address of a
2103 // set of overloaded functions and/or function templates, its
2104 // associated classes and namespaces are the union of those
2105 // associated with each of the members of the set: the namespace
2106 // in which the function or function template is defined and the
2107 // classes and namespaces associated with its (non-dependent)
2108 // parameter types and return type.
2109 Arg = Arg->IgnoreParens();
2110 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2111 if (unaryOp->getOpcode() == UO_AddrOf)
2112 Arg = unaryOp->getSubExpr();
2114 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2117 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2119 // Look through any using declarations to find the underlying function.
2120 NamedDecl *Fn = (*I)->getUnderlyingDecl();
2122 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2124 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2126 // Add the classes and namespaces associated with the parameter
2127 // types and return type of this function.
2128 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2133 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2134 /// an acceptable non-member overloaded operator for a call whose
2135 /// arguments have types T1 (and, if non-empty, T2). This routine
2136 /// implements the check in C++ [over.match.oper]p3b2 concerning
2137 /// enumeration types.
2139 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2140 QualType T1, QualType T2,
2141 ASTContext &Context) {
2142 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2145 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2148 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2149 if (Proto->getNumArgs() < 1)
2152 if (T1->isEnumeralType()) {
2153 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2154 if (Context.hasSameUnqualifiedType(T1, ArgType))
2158 if (Proto->getNumArgs() < 2)
2161 if (!T2.isNull() && T2->isEnumeralType()) {
2162 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2163 if (Context.hasSameUnqualifiedType(T2, ArgType))
2170 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2172 LookupNameKind NameKind,
2173 RedeclarationKind Redecl) {
2174 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2176 return R.getAsSingle<NamedDecl>();
2179 /// \brief Find the protocol with the given name, if any.
2180 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2181 SourceLocation IdLoc,
2182 RedeclarationKind Redecl) {
2183 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2184 LookupObjCProtocolName, Redecl);
2185 return cast_or_null<ObjCProtocolDecl>(D);
2188 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2189 QualType T1, QualType T2,
2190 UnresolvedSetImpl &Functions) {
2191 // C++ [over.match.oper]p3:
2192 // -- The set of non-member candidates is the result of the
2193 // unqualified lookup of operator@ in the context of the
2194 // expression according to the usual rules for name lookup in
2195 // unqualified function calls (3.4.2) except that all member
2196 // functions are ignored. However, if no operand has a class
2197 // type, only those non-member functions in the lookup set
2198 // that have a first parameter of type T1 or "reference to
2199 // (possibly cv-qualified) T1", when T1 is an enumeration
2200 // type, or (if there is a right operand) a second parameter
2201 // of type T2 or "reference to (possibly cv-qualified) T2",
2202 // when T2 is an enumeration type, are candidate functions.
2203 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2204 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2205 LookupName(Operators, S);
2207 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2209 if (Operators.empty())
2212 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2213 Op != OpEnd; ++Op) {
2214 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2215 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2216 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2217 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2218 } else if (FunctionTemplateDecl *FunTmpl
2219 = dyn_cast<FunctionTemplateDecl>(Found)) {
2220 // FIXME: friend operators?
2221 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2223 if (!FunTmpl->getDeclContext()->isRecord())
2224 Functions.addDecl(*Op, Op.getAccess());
2229 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
2230 CXXSpecialMember SM,
2235 bool VolatileThis) {
2236 RD = RD->getDefinition();
2237 assert((RD && !RD->isBeingDefined()) &&
2238 "doing special member lookup into record that isn't fully complete");
2239 if (RValueThis || ConstThis || VolatileThis)
2240 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2241 "constructors and destructors always have unqualified lvalue this");
2242 if (ConstArg || VolatileArg)
2243 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2244 "parameter-less special members can't have qualified arguments");
2246 llvm::FoldingSetNodeID ID;
2249 ID.AddInteger(ConstArg);
2250 ID.AddInteger(VolatileArg);
2251 ID.AddInteger(RValueThis);
2252 ID.AddInteger(ConstThis);
2253 ID.AddInteger(VolatileThis);
2256 SpecialMemberOverloadResult *Result =
2257 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2259 // This was already cached
2263 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2264 Result = new (Result) SpecialMemberOverloadResult(ID);
2265 SpecialMemberCache.InsertNode(Result, InsertPoint);
2267 if (SM == CXXDestructor) {
2268 if (!RD->hasDeclaredDestructor())
2269 DeclareImplicitDestructor(RD);
2270 CXXDestructorDecl *DD = RD->getDestructor();
2271 assert(DD && "record without a destructor");
2272 Result->setMethod(DD);
2273 Result->setKind(DD->isDeleted() ?
2274 SpecialMemberOverloadResult::NoMemberOrDeleted :
2275 SpecialMemberOverloadResult::Success);
2279 // Prepare for overload resolution. Here we construct a synthetic argument
2280 // if necessary and make sure that implicit functions are declared.
2281 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2282 DeclarationName Name;
2286 QualType ArgType = CanTy;
2287 ExprValueKind VK = VK_LValue;
2289 if (SM == CXXDefaultConstructor) {
2290 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2292 if (RD->needsImplicitDefaultConstructor())
2293 DeclareImplicitDefaultConstructor(RD);
2295 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2296 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2297 if (!RD->hasDeclaredCopyConstructor())
2298 DeclareImplicitCopyConstructor(RD);
2299 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveConstructor())
2300 DeclareImplicitMoveConstructor(RD);
2302 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2303 if (!RD->hasDeclaredCopyAssignment())
2304 DeclareImplicitCopyAssignment(RD);
2305 if (getLangOpts().CPlusPlus0x && RD->needsImplicitMoveAssignment())
2306 DeclareImplicitMoveAssignment(RD);
2312 ArgType.addVolatile();
2314 // This isn't /really/ specified by the standard, but it's implied
2315 // we should be working from an RValue in the case of move to ensure
2316 // that we prefer to bind to rvalue references, and an LValue in the
2317 // case of copy to ensure we don't bind to rvalue references.
2318 // Possibly an XValue is actually correct in the case of move, but
2319 // there is no semantic difference for class types in this restricted
2321 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2327 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2329 if (SM != CXXDefaultConstructor) {
2334 // Create the object argument
2335 QualType ThisTy = CanTy;
2339 ThisTy.addVolatile();
2340 Expr::Classification Classification =
2341 OpaqueValueExpr(SourceLocation(), ThisTy,
2342 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
2344 // Now we perform lookup on the name we computed earlier and do overload
2345 // resolution. Lookup is only performed directly into the class since there
2346 // will always be a (possibly implicit) declaration to shadow any others.
2347 OverloadCandidateSet OCS((SourceLocation()));
2348 DeclContext::lookup_iterator I, E;
2350 llvm::tie(I, E) = RD->lookup(Name);
2352 "lookup for a constructor or assignment operator was empty");
2353 for ( ; I != E; ++I) {
2356 if (Cand->isInvalidDecl())
2359 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2360 // FIXME: [namespace.udecl]p15 says that we should only consider a
2361 // using declaration here if it does not match a declaration in the
2362 // derived class. We do not implement this correctly in other cases
2364 Cand = U->getTargetDecl();
2366 if (Cand->isInvalidDecl())
2370 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
2371 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2372 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
2373 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2376 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2377 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2378 } else if (FunctionTemplateDecl *Tmpl =
2379 dyn_cast<FunctionTemplateDecl>(Cand)) {
2380 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2381 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2382 RD, 0, ThisTy, Classification,
2383 llvm::makeArrayRef(&Arg, NumArgs),
2386 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2387 0, llvm::makeArrayRef(&Arg, NumArgs),
2390 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
2394 OverloadCandidateSet::iterator Best;
2395 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2397 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2398 Result->setKind(SpecialMemberOverloadResult::Success);
2402 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2403 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2407 Result->setMethod(0);
2408 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2411 case OR_No_Viable_Function:
2412 Result->setMethod(0);
2413 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2420 /// \brief Look up the default constructor for the given class.
2421 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
2422 SpecialMemberOverloadResult *Result =
2423 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2426 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2429 /// \brief Look up the copying constructor for the given class.
2430 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2432 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2433 "non-const, non-volatile qualifiers for copy ctor arg");
2434 SpecialMemberOverloadResult *Result =
2435 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2436 Quals & Qualifiers::Volatile, false, false, false);
2438 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2441 /// \brief Look up the moving constructor for the given class.
2442 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2444 SpecialMemberOverloadResult *Result =
2445 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2446 Quals & Qualifiers::Volatile, false, false, false);
2448 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2451 /// \brief Look up the constructors for the given class.
2452 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2453 // If the implicit constructors have not yet been declared, do so now.
2454 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2455 if (Class->needsImplicitDefaultConstructor())
2456 DeclareImplicitDefaultConstructor(Class);
2457 if (!Class->hasDeclaredCopyConstructor())
2458 DeclareImplicitCopyConstructor(Class);
2459 if (getLangOpts().CPlusPlus0x && Class->needsImplicitMoveConstructor())
2460 DeclareImplicitMoveConstructor(Class);
2463 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2464 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2465 return Class->lookup(Name);
2468 /// \brief Look up the copying assignment operator for the given class.
2469 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2470 unsigned Quals, bool RValueThis,
2471 unsigned ThisQuals) {
2472 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2473 "non-const, non-volatile qualifiers for copy assignment arg");
2474 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2475 "non-const, non-volatile qualifiers for copy assignment this");
2476 SpecialMemberOverloadResult *Result =
2477 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2478 Quals & Qualifiers::Volatile, RValueThis,
2479 ThisQuals & Qualifiers::Const,
2480 ThisQuals & Qualifiers::Volatile);
2482 return Result->getMethod();
2485 /// \brief Look up the moving assignment operator for the given class.
2486 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2489 unsigned ThisQuals) {
2490 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2491 "non-const, non-volatile qualifiers for copy assignment this");
2492 SpecialMemberOverloadResult *Result =
2493 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2494 Quals & Qualifiers::Volatile, RValueThis,
2495 ThisQuals & Qualifiers::Const,
2496 ThisQuals & Qualifiers::Volatile);
2498 return Result->getMethod();
2501 /// \brief Look for the destructor of the given class.
2503 /// During semantic analysis, this routine should be used in lieu of
2504 /// CXXRecordDecl::getDestructor().
2506 /// \returns The destructor for this class.
2507 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2508 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2509 false, false, false,
2510 false, false)->getMethod());
2513 /// LookupLiteralOperator - Determine which literal operator should be used for
2514 /// a user-defined literal, per C++11 [lex.ext].
2516 /// Normal overload resolution is not used to select which literal operator to
2517 /// call for a user-defined literal. Look up the provided literal operator name,
2518 /// and filter the results to the appropriate set for the given argument types.
2519 Sema::LiteralOperatorLookupResult
2520 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2521 ArrayRef<QualType> ArgTys,
2522 bool AllowRawAndTemplate) {
2524 assert(R.getResultKind() != LookupResult::Ambiguous &&
2525 "literal operator lookup can't be ambiguous");
2527 // Filter the lookup results appropriately.
2528 LookupResult::Filter F = R.makeFilter();
2530 bool FoundTemplate = false;
2531 bool FoundRaw = false;
2532 bool FoundExactMatch = false;
2534 while (F.hasNext()) {
2536 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2537 D = USD->getTargetDecl();
2539 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2541 bool IsExactMatch = false;
2543 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2544 if (FD->getNumParams() == 1 &&
2545 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2548 IsExactMatch = true;
2549 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2550 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2551 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2552 IsExactMatch = false;
2560 FoundExactMatch = true;
2561 AllowRawAndTemplate = false;
2562 if (FoundRaw || FoundTemplate) {
2563 // Go through again and remove the raw and template decls we've
2566 FoundRaw = FoundTemplate = false;
2568 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2569 FoundTemplate |= IsTemplate;
2578 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2579 // parameter type, that is used in preference to a raw literal operator
2580 // or literal operator template.
2581 if (FoundExactMatch)
2584 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2585 // operator template, but not both.
2586 if (FoundRaw && FoundTemplate) {
2587 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2588 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2590 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2591 D = USD->getTargetDecl();
2592 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2593 D = FunTmpl->getTemplatedDecl();
2594 NoteOverloadCandidate(cast<FunctionDecl>(D));
2603 return LOLR_Template;
2605 // Didn't find anything we could use.
2606 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2607 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2608 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2612 void ADLResult::insert(NamedDecl *New) {
2613 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2615 // If we haven't yet seen a decl for this key, or the last decl
2616 // was exactly this one, we're done.
2617 if (Old == 0 || Old == New) {
2622 // Otherwise, decide which is a more recent redeclaration.
2623 FunctionDecl *OldFD, *NewFD;
2624 if (isa<FunctionTemplateDecl>(New)) {
2625 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2626 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2628 OldFD = cast<FunctionDecl>(Old);
2629 NewFD = cast<FunctionDecl>(New);
2632 FunctionDecl *Cursor = NewFD;
2634 Cursor = Cursor->getPreviousDecl();
2636 // If we got to the end without finding OldFD, OldFD is the newer
2637 // declaration; leave things as they are.
2638 if (!Cursor) return;
2640 // If we do find OldFD, then NewFD is newer.
2641 if (Cursor == OldFD) break;
2643 // Otherwise, keep looking.
2649 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2651 llvm::ArrayRef<Expr *> Args,
2652 ADLResult &Result) {
2653 // Find all of the associated namespaces and classes based on the
2654 // arguments we have.
2655 AssociatedNamespaceSet AssociatedNamespaces;
2656 AssociatedClassSet AssociatedClasses;
2657 FindAssociatedClassesAndNamespaces(Loc, Args,
2658 AssociatedNamespaces,
2663 T1 = Args[0]->getType();
2664 if (Args.size() >= 2)
2665 T2 = Args[1]->getType();
2668 // C++ [basic.lookup.argdep]p3:
2669 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2670 // and let Y be the lookup set produced by argument dependent
2671 // lookup (defined as follows). If X contains [...] then Y is
2672 // empty. Otherwise Y is the set of declarations found in the
2673 // namespaces associated with the argument types as described
2674 // below. The set of declarations found by the lookup of the name
2675 // is the union of X and Y.
2677 // Here, we compute Y and add its members to the overloaded
2679 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2680 NSEnd = AssociatedNamespaces.end();
2681 NS != NSEnd; ++NS) {
2682 // When considering an associated namespace, the lookup is the
2683 // same as the lookup performed when the associated namespace is
2684 // used as a qualifier (3.4.3.2) except that:
2686 // -- Any using-directives in the associated namespace are
2689 // -- Any namespace-scope friend functions declared in
2690 // associated classes are visible within their respective
2691 // namespaces even if they are not visible during an ordinary
2693 DeclContext::lookup_iterator I, E;
2694 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
2696 // If the only declaration here is an ordinary friend, consider
2697 // it only if it was declared in an associated classes.
2698 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
2699 DeclContext *LexDC = D->getLexicalDeclContext();
2700 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2704 if (isa<UsingShadowDecl>(D))
2705 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2707 if (isa<FunctionDecl>(D)) {
2709 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2712 } else if (!isa<FunctionTemplateDecl>(D))
2720 //----------------------------------------------------------------------------
2721 // Search for all visible declarations.
2722 //----------------------------------------------------------------------------
2723 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2727 class ShadowContextRAII;
2729 class VisibleDeclsRecord {
2731 /// \brief An entry in the shadow map, which is optimized to store a
2732 /// single declaration (the common case) but can also store a list
2733 /// of declarations.
2734 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
2737 /// \brief A mapping from declaration names to the declarations that have
2738 /// this name within a particular scope.
2739 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2741 /// \brief A list of shadow maps, which is used to model name hiding.
2742 std::list<ShadowMap> ShadowMaps;
2744 /// \brief The declaration contexts we have already visited.
2745 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2747 friend class ShadowContextRAII;
2750 /// \brief Determine whether we have already visited this context
2751 /// (and, if not, note that we are going to visit that context now).
2752 bool visitedContext(DeclContext *Ctx) {
2753 return !VisitedContexts.insert(Ctx);
2756 bool alreadyVisitedContext(DeclContext *Ctx) {
2757 return VisitedContexts.count(Ctx);
2760 /// \brief Determine whether the given declaration is hidden in the
2763 /// \returns the declaration that hides the given declaration, or
2764 /// NULL if no such declaration exists.
2765 NamedDecl *checkHidden(NamedDecl *ND);
2767 /// \brief Add a declaration to the current shadow map.
2768 void add(NamedDecl *ND) {
2769 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2773 /// \brief RAII object that records when we've entered a shadow context.
2774 class ShadowContextRAII {
2775 VisibleDeclsRecord &Visible;
2777 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2780 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2781 Visible.ShadowMaps.push_back(ShadowMap());
2784 ~ShadowContextRAII() {
2785 Visible.ShadowMaps.pop_back();
2789 } // end anonymous namespace
2791 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2792 // Look through using declarations.
2793 ND = ND->getUnderlyingDecl();
2795 unsigned IDNS = ND->getIdentifierNamespace();
2796 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2797 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2798 SM != SMEnd; ++SM) {
2799 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2800 if (Pos == SM->end())
2803 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2804 IEnd = Pos->second.end();
2806 // A tag declaration does not hide a non-tag declaration.
2807 if ((*I)->hasTagIdentifierNamespace() &&
2808 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2809 Decl::IDNS_ObjCProtocol)))
2812 // Protocols are in distinct namespaces from everything else.
2813 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2814 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2815 (*I)->getIdentifierNamespace() != IDNS)
2818 // Functions and function templates in the same scope overload
2819 // rather than hide. FIXME: Look for hiding based on function
2821 if ((*I)->isFunctionOrFunctionTemplate() &&
2822 ND->isFunctionOrFunctionTemplate() &&
2823 SM == ShadowMaps.rbegin())
2826 // We've found a declaration that hides this one.
2834 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2835 bool QualifiedNameLookup,
2837 VisibleDeclConsumer &Consumer,
2838 VisibleDeclsRecord &Visited) {
2842 // Make sure we don't visit the same context twice.
2843 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2846 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2847 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2849 // Enumerate all of the results in this context.
2850 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2851 LEnd = Ctx->lookups_end();
2853 for (DeclContext::lookup_result R = *L; R.first != R.second; ++R.first) {
2854 if (NamedDecl *ND = dyn_cast<NamedDecl>(*R.first)) {
2855 if ((ND = Result.getAcceptableDecl(ND))) {
2856 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
2863 // Traverse using directives for qualified name lookup.
2864 if (QualifiedNameLookup) {
2865 ShadowContextRAII Shadow(Visited);
2866 DeclContext::udir_iterator I, E;
2867 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2868 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
2869 QualifiedNameLookup, InBaseClass, Consumer, Visited);
2873 // Traverse the contexts of inherited C++ classes.
2874 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2875 if (!Record->hasDefinition())
2878 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2879 BEnd = Record->bases_end();
2881 QualType BaseType = B->getType();
2883 // Don't look into dependent bases, because name lookup can't look
2885 if (BaseType->isDependentType())
2888 const RecordType *Record = BaseType->getAs<RecordType>();
2892 // FIXME: It would be nice to be able to determine whether referencing
2893 // a particular member would be ambiguous. For example, given
2895 // struct A { int member; };
2896 // struct B { int member; };
2897 // struct C : A, B { };
2899 // void f(C *c) { c->### }
2901 // accessing 'member' would result in an ambiguity. However, we
2902 // could be smart enough to qualify the member with the base
2911 // Find results in this base class (and its bases).
2912 ShadowContextRAII Shadow(Visited);
2913 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2914 true, Consumer, Visited);
2918 // Traverse the contexts of Objective-C classes.
2919 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2920 // Traverse categories.
2921 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2922 Category; Category = Category->getNextClassCategory()) {
2923 ShadowContextRAII Shadow(Visited);
2924 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2928 // Traverse protocols.
2929 for (ObjCInterfaceDecl::all_protocol_iterator
2930 I = IFace->all_referenced_protocol_begin(),
2931 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
2932 ShadowContextRAII Shadow(Visited);
2933 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2937 // Traverse the superclass.
2938 if (IFace->getSuperClass()) {
2939 ShadowContextRAII Shadow(Visited);
2940 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
2941 true, Consumer, Visited);
2944 // If there is an implementation, traverse it. We do this to find
2945 // synthesized ivars.
2946 if (IFace->getImplementation()) {
2947 ShadowContextRAII Shadow(Visited);
2948 LookupVisibleDecls(IFace->getImplementation(), Result,
2949 QualifiedNameLookup, InBaseClass, Consumer, Visited);
2951 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2952 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2953 E = Protocol->protocol_end(); I != E; ++I) {
2954 ShadowContextRAII Shadow(Visited);
2955 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2958 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2959 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2960 E = Category->protocol_end(); I != E; ++I) {
2961 ShadowContextRAII Shadow(Visited);
2962 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2966 // If there is an implementation, traverse it.
2967 if (Category->getImplementation()) {
2968 ShadowContextRAII Shadow(Visited);
2969 LookupVisibleDecls(Category->getImplementation(), Result,
2970 QualifiedNameLookup, true, Consumer, Visited);
2975 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2976 UnqualUsingDirectiveSet &UDirs,
2977 VisibleDeclConsumer &Consumer,
2978 VisibleDeclsRecord &Visited) {
2982 if (!S->getEntity() ||
2984 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
2985 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2986 // Walk through the declarations in this Scope.
2987 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2989 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2990 if ((ND = Result.getAcceptableDecl(ND))) {
2991 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
2997 // FIXME: C++ [temp.local]p8
2998 DeclContext *Entity = 0;
2999 if (S->getEntity()) {
3000 // Look into this scope's declaration context, along with any of its
3001 // parent lookup contexts (e.g., enclosing classes), up to the point
3002 // where we hit the context stored in the next outer scope.
3003 Entity = (DeclContext *)S->getEntity();
3004 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3006 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3007 Ctx = Ctx->getLookupParent()) {
3008 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3009 if (Method->isInstanceMethod()) {
3010 // For instance methods, look for ivars in the method's interface.
3011 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3012 Result.getNameLoc(), Sema::LookupMemberName);
3013 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3014 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3015 /*InBaseClass=*/false, Consumer, Visited);
3019 // We've already performed all of the name lookup that we need
3020 // to for Objective-C methods; the next context will be the
3025 if (Ctx->isFunctionOrMethod())
3028 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3029 /*InBaseClass=*/false, Consumer, Visited);
3031 } else if (!S->getParent()) {
3032 // Look into the translation unit scope. We walk through the translation
3033 // unit's declaration context, because the Scope itself won't have all of
3034 // the declarations if we loaded a precompiled header.
3035 // FIXME: We would like the translation unit's Scope object to point to the
3036 // translation unit, so we don't need this special "if" branch. However,
3037 // doing so would force the normal C++ name-lookup code to look into the
3038 // translation unit decl when the IdentifierInfo chains would suffice.
3039 // Once we fix that problem (which is part of a more general "don't look
3040 // in DeclContexts unless we have to" optimization), we can eliminate this.
3041 Entity = Result.getSema().Context.getTranslationUnitDecl();
3042 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3043 /*InBaseClass=*/false, Consumer, Visited);
3047 // Lookup visible declarations in any namespaces found by using
3049 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3050 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3051 for (; UI != UEnd; ++UI)
3052 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
3053 Result, /*QualifiedNameLookup=*/false,
3054 /*InBaseClass=*/false, Consumer, Visited);
3057 // Lookup names in the parent scope.
3058 ShadowContextRAII Shadow(Visited);
3059 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3062 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3063 VisibleDeclConsumer &Consumer,
3064 bool IncludeGlobalScope) {
3065 // Determine the set of using directives available during
3066 // unqualified name lookup.
3068 UnqualUsingDirectiveSet UDirs;
3069 if (getLangOpts().CPlusPlus) {
3070 // Find the first namespace or translation-unit scope.
3071 while (S && !isNamespaceOrTranslationUnitScope(S))
3074 UDirs.visitScopeChain(Initial, S);
3078 // Look for visible declarations.
3079 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3080 VisibleDeclsRecord Visited;
3081 if (!IncludeGlobalScope)
3082 Visited.visitedContext(Context.getTranslationUnitDecl());
3083 ShadowContextRAII Shadow(Visited);
3084 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3087 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3088 VisibleDeclConsumer &Consumer,
3089 bool IncludeGlobalScope) {
3090 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3091 VisibleDeclsRecord Visited;
3092 if (!IncludeGlobalScope)
3093 Visited.visitedContext(Context.getTranslationUnitDecl());
3094 ShadowContextRAII Shadow(Visited);
3095 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3096 /*InBaseClass=*/false, Consumer, Visited);
3099 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3100 /// If GnuLabelLoc is a valid source location, then this is a definition
3101 /// of an __label__ label name, otherwise it is a normal label definition
3103 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3104 SourceLocation GnuLabelLoc) {
3105 // Do a lookup to see if we have a label with this name already.
3108 if (GnuLabelLoc.isValid()) {
3109 // Local label definitions always shadow existing labels.
3110 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3111 Scope *S = CurScope;
3112 PushOnScopeChains(Res, S, true);
3113 return cast<LabelDecl>(Res);
3116 // Not a GNU local label.
3117 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3118 // If we found a label, check to see if it is in the same context as us.
3119 // When in a Block, we don't want to reuse a label in an enclosing function.
3120 if (Res && Res->getDeclContext() != CurContext)
3123 // If not forward referenced or defined already, create the backing decl.
3124 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3125 Scope *S = CurScope->getFnParent();
3126 assert(S && "Not in a function?");
3127 PushOnScopeChains(Res, S, true);
3129 return cast<LabelDecl>(Res);
3132 //===----------------------------------------------------------------------===//
3134 //===----------------------------------------------------------------------===//
3138 typedef llvm::SmallVector<TypoCorrection, 1> TypoResultList;
3139 typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
3140 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
3142 static const unsigned MaxTypoDistanceResultSets = 5;
3144 class TypoCorrectionConsumer : public VisibleDeclConsumer {
3145 /// \brief The name written that is a typo in the source.
3148 /// \brief The results found that have the smallest edit distance
3149 /// found (so far) with the typo name.
3151 /// The pointer value being set to the current DeclContext indicates
3152 /// whether there is a keyword with this name.
3153 TypoEditDistanceMap CorrectionResults;
3158 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
3159 : Typo(Typo->getName()),
3160 SemaRef(SemaRef) { }
3162 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3164 void FoundName(StringRef Name);
3165 void addKeywordResult(StringRef Keyword);
3166 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
3167 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
3168 void addCorrection(TypoCorrection Correction);
3170 typedef TypoResultsMap::iterator result_iterator;
3171 typedef TypoEditDistanceMap::iterator distance_iterator;
3172 distance_iterator begin() { return CorrectionResults.begin(); }
3173 distance_iterator end() { return CorrectionResults.end(); }
3174 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3175 unsigned size() const { return CorrectionResults.size(); }
3176 bool empty() const { return CorrectionResults.empty(); }
3178 TypoResultList &operator[](StringRef Name) {
3179 return CorrectionResults.begin()->second[Name];
3182 unsigned getBestEditDistance(bool Normalized) {
3183 if (CorrectionResults.empty())
3184 return (std::numeric_limits<unsigned>::max)();
3186 unsigned BestED = CorrectionResults.begin()->first;
3187 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
3190 TypoResultsMap &getBestResults() {
3191 return CorrectionResults.begin()->second;
3198 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3199 DeclContext *Ctx, bool InBaseClass) {
3200 // Don't consider hidden names for typo correction.
3204 // Only consider entities with identifiers for names, ignoring
3205 // special names (constructors, overloaded operators, selectors,
3207 IdentifierInfo *Name = ND->getIdentifier();
3211 FoundName(Name->getName());
3214 void TypoCorrectionConsumer::FoundName(StringRef Name) {
3215 // Use a simple length-based heuristic to determine the minimum possible
3216 // edit distance. If the minimum isn't good enough, bail out early.
3217 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
3218 if (MinED && Typo.size() / MinED < 3)
3221 // Compute an upper bound on the allowable edit distance, so that the
3222 // edit-distance algorithm can short-circuit.
3223 unsigned UpperBound = (Typo.size() + 2) / 3;
3225 // Compute the edit distance between the typo and the name of this
3226 // entity, and add the identifier to the list of results.
3227 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
3230 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3231 // Compute the edit distance between the typo and this keyword,
3232 // and add the keyword to the list of results.
3233 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
3236 void TypoCorrectionConsumer::addName(StringRef Name,
3239 NestedNameSpecifier *NNS,
3241 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3242 if (isKeyword) TC.makeKeyword();
3246 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3247 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3248 TypoResultList &CList =
3249 CorrectionResults[Correction.getEditDistance(false)][Name];
3251 if (!CList.empty() && !CList.back().isResolved())
3253 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3254 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3255 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3256 RI != RIEnd; ++RI) {
3257 // If the Correction refers to a decl already in the result list,
3258 // replace the existing result if the string representation of Correction
3259 // comes before the current result alphabetically, then stop as there is
3260 // nothing more to be done to add Correction to the candidate set.
3261 if (RI->getCorrectionDecl() == NewND) {
3262 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3268 if (CList.empty() || Correction.isResolved())
3269 CList.push_back(Correction);
3271 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3272 erase(llvm::prior(CorrectionResults.end()));
3275 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
3276 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3277 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3278 static void getNestedNameSpecifierIdentifiers(
3279 NestedNameSpecifier *NNS,
3280 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3281 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3282 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3284 Identifiers.clear();
3286 const IdentifierInfo *II = NULL;
3288 switch (NNS->getKind()) {
3289 case NestedNameSpecifier::Identifier:
3290 II = NNS->getAsIdentifier();
3293 case NestedNameSpecifier::Namespace:
3294 if (NNS->getAsNamespace()->isAnonymousNamespace())
3296 II = NNS->getAsNamespace()->getIdentifier();
3299 case NestedNameSpecifier::NamespaceAlias:
3300 II = NNS->getAsNamespaceAlias()->getIdentifier();
3303 case NestedNameSpecifier::TypeSpecWithTemplate:
3304 case NestedNameSpecifier::TypeSpec:
3305 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3308 case NestedNameSpecifier::Global:
3313 Identifiers.push_back(II);
3318 class SpecifierInfo {
3320 DeclContext* DeclCtx;
3321 NestedNameSpecifier* NameSpecifier;
3322 unsigned EditDistance;
3324 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3325 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3328 typedef SmallVector<DeclContext*, 4> DeclContextList;
3329 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3331 class NamespaceSpecifierSet {
3332 ASTContext &Context;
3333 DeclContextList CurContextChain;
3334 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3335 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
3338 SpecifierInfoList Specifiers;
3339 llvm::SmallSetVector<unsigned, 4> Distances;
3340 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3342 /// \brief Helper for building the list of DeclContexts between the current
3343 /// context and the top of the translation unit
3344 static DeclContextList BuildContextChain(DeclContext *Start);
3346 void SortNamespaces();
3349 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3350 CXXScopeSpec *CurScopeSpec)
3351 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3353 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3354 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3355 CurNameSpecifierIdentifiers);
3356 // Build the list of identifiers that would be used for an absolute
3357 // (from the global context) NestedNameSpecifier referring to the current
3359 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3360 CEnd = CurContextChain.rend();
3362 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3363 CurContextIdentifiers.push_back(ND->getIdentifier());
3367 /// \brief Add the namespace to the set, computing the corresponding
3368 /// NestedNameSpecifier and its distance in the process.
3369 void AddNamespace(NamespaceDecl *ND);
3371 typedef SpecifierInfoList::iterator iterator;
3373 if (!isSorted) SortNamespaces();
3374 return Specifiers.begin();
3376 iterator end() { return Specifiers.end(); }
3381 DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
3382 assert(Start && "Bulding a context chain from a null context");
3383 DeclContextList Chain;
3384 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3385 DC = DC->getLookupParent()) {
3386 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3387 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3388 !(ND && ND->isAnonymousNamespace()))
3389 Chain.push_back(DC->getPrimaryContext());
3394 void NamespaceSpecifierSet::SortNamespaces() {
3395 SmallVector<unsigned, 4> sortedDistances;
3396 sortedDistances.append(Distances.begin(), Distances.end());
3398 if (sortedDistances.size() > 1)
3399 std::sort(sortedDistances.begin(), sortedDistances.end());
3402 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
3403 DIEnd = sortedDistances.end();
3404 DI != DIEnd; ++DI) {
3405 SpecifierInfoList &SpecList = DistanceMap[*DI];
3406 Specifiers.append(SpecList.begin(), SpecList.end());
3412 void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
3413 DeclContext *Ctx = cast<DeclContext>(ND);
3414 NestedNameSpecifier *NNS = NULL;
3415 unsigned NumSpecifiers = 0;
3416 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3417 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3419 // Eliminate common elements from the two DeclContext chains.
3420 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3421 CEnd = CurContextChain.rend();
3422 C != CEnd && !NamespaceDeclChain.empty() &&
3423 NamespaceDeclChain.back() == *C; ++C) {
3424 NamespaceDeclChain.pop_back();
3427 // Add an explicit leading '::' specifier if needed.
3428 if (NamespaceDecl *ND =
3429 NamespaceDeclChain.empty() ? NULL :
3430 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
3431 IdentifierInfo *Name = ND->getIdentifier();
3432 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3433 Name) != CurContextIdentifiers.end() ||
3434 std::find(CurNameSpecifierIdentifiers.begin(),
3435 CurNameSpecifierIdentifiers.end(),
3436 Name) != CurNameSpecifierIdentifiers.end()) {
3437 NamespaceDeclChain = FullNamespaceDeclChain;
3438 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3442 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3443 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3444 CEnd = NamespaceDeclChain.rend();
3446 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3448 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3453 // If the built NestedNameSpecifier would be replacing an existing
3454 // NestedNameSpecifier, use the number of component identifiers that
3455 // would need to be changed as the edit distance instead of the number
3456 // of components in the built NestedNameSpecifier.
3457 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3458 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3459 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3460 NumSpecifiers = llvm::ComputeEditDistance(
3461 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3462 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3466 Distances.insert(NumSpecifiers);
3467 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3470 /// \brief Perform name lookup for a possible result for typo correction.
3471 static void LookupPotentialTypoResult(Sema &SemaRef,
3473 IdentifierInfo *Name,
3474 Scope *S, CXXScopeSpec *SS,
3475 DeclContext *MemberContext,
3476 bool EnteringContext,
3477 bool isObjCIvarLookup) {
3478 Res.suppressDiagnostics();
3480 Res.setLookupName(Name);
3481 if (MemberContext) {
3482 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3483 if (isObjCIvarLookup) {
3484 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3491 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3498 SemaRef.LookupQualifiedName(Res, MemberContext);
3502 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3505 // Fake ivar lookup; this should really be part of
3506 // LookupParsedName.
3507 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3508 if (Method->isInstanceMethod() && Method->getClassInterface() &&
3510 (Res.isSingleResult() &&
3511 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3512 if (ObjCIvarDecl *IV
3513 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3521 /// \brief Add keywords to the consumer as possible typo corrections.
3522 static void AddKeywordsToConsumer(Sema &SemaRef,
3523 TypoCorrectionConsumer &Consumer,
3524 Scope *S, CorrectionCandidateCallback &CCC,
3525 bool AfterNestedNameSpecifier) {
3526 if (AfterNestedNameSpecifier) {
3527 // For 'X::', we know exactly which keywords can appear next.
3528 Consumer.addKeywordResult("template");
3529 if (CCC.WantExpressionKeywords)
3530 Consumer.addKeywordResult("operator");
3534 if (CCC.WantObjCSuper)
3535 Consumer.addKeywordResult("super");
3537 if (CCC.WantTypeSpecifiers) {
3538 // Add type-specifier keywords to the set of results.
3539 const char *CTypeSpecs[] = {
3540 "char", "const", "double", "enum", "float", "int", "long", "short",
3541 "signed", "struct", "union", "unsigned", "void", "volatile",
3542 "_Complex", "_Imaginary",
3543 // storage-specifiers as well
3544 "extern", "inline", "static", "typedef"
3547 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3548 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3549 Consumer.addKeywordResult(CTypeSpecs[I]);
3551 if (SemaRef.getLangOpts().C99)
3552 Consumer.addKeywordResult("restrict");
3553 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
3554 Consumer.addKeywordResult("bool");
3555 else if (SemaRef.getLangOpts().C99)
3556 Consumer.addKeywordResult("_Bool");
3558 if (SemaRef.getLangOpts().CPlusPlus) {
3559 Consumer.addKeywordResult("class");
3560 Consumer.addKeywordResult("typename");
3561 Consumer.addKeywordResult("wchar_t");
3563 if (SemaRef.getLangOpts().CPlusPlus0x) {
3564 Consumer.addKeywordResult("char16_t");
3565 Consumer.addKeywordResult("char32_t");
3566 Consumer.addKeywordResult("constexpr");
3567 Consumer.addKeywordResult("decltype");
3568 Consumer.addKeywordResult("thread_local");
3572 if (SemaRef.getLangOpts().GNUMode)
3573 Consumer.addKeywordResult("typeof");
3576 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
3577 Consumer.addKeywordResult("const_cast");
3578 Consumer.addKeywordResult("dynamic_cast");
3579 Consumer.addKeywordResult("reinterpret_cast");
3580 Consumer.addKeywordResult("static_cast");
3583 if (CCC.WantExpressionKeywords) {
3584 Consumer.addKeywordResult("sizeof");
3585 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
3586 Consumer.addKeywordResult("false");
3587 Consumer.addKeywordResult("true");
3590 if (SemaRef.getLangOpts().CPlusPlus) {
3591 const char *CXXExprs[] = {
3592 "delete", "new", "operator", "throw", "typeid"
3594 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3595 for (unsigned I = 0; I != NumCXXExprs; ++I)
3596 Consumer.addKeywordResult(CXXExprs[I]);
3598 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3599 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3600 Consumer.addKeywordResult("this");
3602 if (SemaRef.getLangOpts().CPlusPlus0x) {
3603 Consumer.addKeywordResult("alignof");
3604 Consumer.addKeywordResult("nullptr");
3608 if (SemaRef.getLangOpts().C11) {
3609 // FIXME: We should not suggest _Alignof if the alignof macro
3611 Consumer.addKeywordResult("_Alignof");
3615 if (CCC.WantRemainingKeywords) {
3616 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3618 const char *CStmts[] = {
3619 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3620 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3621 for (unsigned I = 0; I != NumCStmts; ++I)
3622 Consumer.addKeywordResult(CStmts[I]);
3624 if (SemaRef.getLangOpts().CPlusPlus) {
3625 Consumer.addKeywordResult("catch");
3626 Consumer.addKeywordResult("try");
3629 if (S && S->getBreakParent())
3630 Consumer.addKeywordResult("break");
3632 if (S && S->getContinueParent())
3633 Consumer.addKeywordResult("continue");
3635 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3636 Consumer.addKeywordResult("case");
3637 Consumer.addKeywordResult("default");
3640 if (SemaRef.getLangOpts().CPlusPlus) {
3641 Consumer.addKeywordResult("namespace");
3642 Consumer.addKeywordResult("template");
3645 if (S && S->isClassScope()) {
3646 Consumer.addKeywordResult("explicit");
3647 Consumer.addKeywordResult("friend");
3648 Consumer.addKeywordResult("mutable");
3649 Consumer.addKeywordResult("private");
3650 Consumer.addKeywordResult("protected");
3651 Consumer.addKeywordResult("public");
3652 Consumer.addKeywordResult("virtual");
3656 if (SemaRef.getLangOpts().CPlusPlus) {
3657 Consumer.addKeywordResult("using");
3659 if (SemaRef.getLangOpts().CPlusPlus0x)
3660 Consumer.addKeywordResult("static_assert");
3665 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3666 TypoCorrection &Candidate) {
3667 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3668 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3671 /// \brief Try to "correct" a typo in the source code by finding
3672 /// visible declarations whose names are similar to the name that was
3673 /// present in the source code.
3675 /// \param TypoName the \c DeclarationNameInfo structure that contains
3676 /// the name that was present in the source code along with its location.
3678 /// \param LookupKind the name-lookup criteria used to search for the name.
3680 /// \param S the scope in which name lookup occurs.
3682 /// \param SS the nested-name-specifier that precedes the name we're
3683 /// looking for, if present.
3685 /// \param CCC A CorrectionCandidateCallback object that provides further
3686 /// validation of typo correction candidates. It also provides flags for
3687 /// determining the set of keywords permitted.
3689 /// \param MemberContext if non-NULL, the context in which to look for
3690 /// a member access expression.
3692 /// \param EnteringContext whether we're entering the context described by
3693 /// the nested-name-specifier SS.
3695 /// \param OPT when non-NULL, the search for visible declarations will
3696 /// also walk the protocols in the qualified interfaces of \p OPT.
3698 /// \returns a \c TypoCorrection containing the corrected name if the typo
3699 /// along with information such as the \c NamedDecl where the corrected name
3700 /// was declared, and any additional \c NestedNameSpecifier needed to access
3701 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3702 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3703 Sema::LookupNameKind LookupKind,
3704 Scope *S, CXXScopeSpec *SS,
3705 CorrectionCandidateCallback &CCC,
3706 DeclContext *MemberContext,
3707 bool EnteringContext,
3708 const ObjCObjectPointerType *OPT) {
3709 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
3710 return TypoCorrection();
3712 // In Microsoft mode, don't perform typo correction in a template member
3713 // function dependent context because it interferes with the "lookup into
3714 // dependent bases of class templates" feature.
3715 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
3716 isa<CXXMethodDecl>(CurContext))
3717 return TypoCorrection();
3719 // We only attempt to correct typos for identifiers.
3720 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
3722 return TypoCorrection();
3724 // If the scope specifier itself was invalid, don't try to correct
3726 if (SS && SS->isInvalid())
3727 return TypoCorrection();
3729 // Never try to correct typos during template deduction or
3731 if (!ActiveTemplateInstantiations.empty())
3732 return TypoCorrection();
3734 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
3736 TypoCorrectionConsumer Consumer(*this, Typo);
3738 // If a callback object considers an empty typo correction candidate to be
3739 // viable, assume it does not do any actual validation of the candidates.
3740 TypoCorrection EmptyCorrection;
3741 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
3743 // Perform name lookup to find visible, similarly-named entities.
3744 bool IsUnqualifiedLookup = false;
3745 DeclContext *QualifiedDC = MemberContext;
3746 if (MemberContext) {
3747 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
3749 // Look in qualified interfaces.
3751 for (ObjCObjectPointerType::qual_iterator
3752 I = OPT->qual_begin(), E = OPT->qual_end();
3754 LookupVisibleDecls(*I, LookupKind, Consumer);
3756 } else if (SS && SS->isSet()) {
3757 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3759 return TypoCorrection();
3761 // Provide a stop gap for files that are just seriously broken. Trying
3762 // to correct all typos can turn into a HUGE performance penalty, causing
3763 // some files to take minutes to get rejected by the parser.
3764 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3765 return TypoCorrection();
3768 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
3770 IsUnqualifiedLookup = true;
3771 UnqualifiedTyposCorrectedMap::iterator Cached
3772 = UnqualifiedTyposCorrected.find(Typo);
3773 if (Cached != UnqualifiedTyposCorrected.end()) {
3774 // Add the cached value, unless it's a keyword or fails validation. In the
3775 // keyword case, we'll end up adding the keyword below.
3776 if (Cached->second) {
3777 if (!Cached->second.isKeyword() &&
3778 isCandidateViable(CCC, Cached->second))
3779 Consumer.addCorrection(Cached->second);
3781 // Only honor no-correction cache hits when a callback that will validate
3782 // correction candidates is not being used.
3783 if (!ValidatingCallback)
3784 return TypoCorrection();
3787 if (Cached == UnqualifiedTyposCorrected.end()) {
3788 // Provide a stop gap for files that are just seriously broken. Trying
3789 // to correct all typos can turn into a HUGE performance penalty, causing
3790 // some files to take minutes to get rejected by the parser.
3791 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3792 return TypoCorrection();
3796 // Determine whether we are going to search in the various namespaces for
3798 bool SearchNamespaces
3799 = getLangOpts().CPlusPlus &&
3800 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
3801 // In a few cases we *only* want to search for corrections bases on just
3802 // adding or changing the nested name specifier.
3803 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
3805 if (IsUnqualifiedLookup || SearchNamespaces) {
3806 // For unqualified lookup, look through all of the names that we have
3807 // seen in this translation unit.
3808 // FIXME: Re-add the ability to skip very unlikely potential corrections.
3809 for (IdentifierTable::iterator I = Context.Idents.begin(),
3810 IEnd = Context.Idents.end();
3812 Consumer.FoundName(I->getKey());
3814 // Walk through identifiers in external identifier sources.
3815 // FIXME: Re-add the ability to skip very unlikely potential corrections.
3816 if (IdentifierInfoLookup *External
3817 = Context.Idents.getExternalIdentifierLookup()) {
3818 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
3820 StringRef Name = Iter->Next();
3824 Consumer.FoundName(Name);
3829 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
3831 // If we haven't found anything, we're done.
3832 if (Consumer.empty()) {
3833 // If this was an unqualified lookup, note that no correction was found.
3834 if (IsUnqualifiedLookup)
3835 (void)UnqualifiedTyposCorrected[Typo];
3837 return TypoCorrection();
3840 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3841 // is not more that about a third of the length of the typo's identifier.
3842 unsigned ED = Consumer.getBestEditDistance(true);
3843 if (ED > 0 && Typo->getName().size() / ED < 3) {
3844 // If this was an unqualified lookup, note that no correction was found.
3845 if (IsUnqualifiedLookup)
3846 (void)UnqualifiedTyposCorrected[Typo];
3848 return TypoCorrection();
3851 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3852 // to search those namespaces.
3853 if (SearchNamespaces) {
3854 // Load any externally-known namespaces.
3855 if (ExternalSource && !LoadedExternalKnownNamespaces) {
3856 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
3857 LoadedExternalKnownNamespaces = true;
3858 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3859 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3860 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3863 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator
3864 KNI = KnownNamespaces.begin(),
3865 KNIEnd = KnownNamespaces.end();
3866 KNI != KNIEnd; ++KNI)
3867 Namespaces.AddNamespace(KNI->first);
3870 // Weed out any names that could not be found by name lookup or, if a
3871 // CorrectionCandidateCallback object was provided, failed validation.
3872 llvm::SmallVector<TypoCorrection, 16> QualifiedResults;
3873 LookupResult TmpRes(*this, TypoName, LookupKind);
3874 TmpRes.suppressDiagnostics();
3875 while (!Consumer.empty()) {
3876 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3877 unsigned ED = DI->first;
3878 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3879 IEnd = DI->second.end();
3880 I != IEnd; /* Increment in loop. */) {
3881 // If we only want nested name specifier corrections, ignore potential
3882 // corrections that have a different base identifier from the typo.
3883 if (AllowOnlyNNSChanges &&
3884 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3885 TypoCorrectionConsumer::result_iterator Prev = I;
3887 DI->second.erase(Prev);
3891 // If the item already has been looked up or is a keyword, keep it.
3892 // If a validator callback object was given, drop the correction
3893 // unless it passes validation.
3894 bool Viable = false;
3895 for (TypoResultList::iterator RI = I->second.begin();
3896 RI != I->second.end(); /* Increment in loop. */) {
3897 TypoResultList::iterator Prev = RI;
3899 if (Prev->isResolved()) {
3900 if (!isCandidateViable(CCC, *Prev))
3901 RI = I->second.erase(Prev);
3906 if (Viable || I->second.empty()) {
3907 TypoCorrectionConsumer::result_iterator Prev = I;
3910 DI->second.erase(Prev);
3913 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
3915 // Perform name lookup on this name.
3916 TypoCorrection &Candidate = I->second.front();
3917 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3918 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3919 EnteringContext, CCC.IsObjCIvarLookup);
3921 switch (TmpRes.getResultKind()) {
3922 case LookupResult::NotFound:
3923 case LookupResult::NotFoundInCurrentInstantiation:
3924 case LookupResult::FoundUnresolvedValue:
3925 QualifiedResults.push_back(Candidate);
3926 // We didn't find this name in our scope, or didn't like what we found;
3929 TypoCorrectionConsumer::result_iterator Next = I;
3931 DI->second.erase(I);
3936 case LookupResult::Ambiguous:
3937 // We don't deal with ambiguities.
3938 return TypoCorrection();
3940 case LookupResult::FoundOverloaded: {
3941 TypoCorrectionConsumer::result_iterator Prev = I;
3942 // Store all of the Decls for overloaded symbols
3943 for (LookupResult::iterator TRD = TmpRes.begin(),
3944 TRDEnd = TmpRes.end();
3945 TRD != TRDEnd; ++TRD)
3946 Candidate.addCorrectionDecl(*TRD);
3948 if (!isCandidateViable(CCC, Candidate))
3949 DI->second.erase(Prev);
3953 case LookupResult::Found: {
3954 TypoCorrectionConsumer::result_iterator Prev = I;
3955 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3957 if (!isCandidateViable(CCC, Candidate))
3958 DI->second.erase(Prev);
3965 if (DI->second.empty())
3967 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
3968 // If there are results in the closest possible bucket, stop
3971 // Only perform the qualified lookups for C++
3972 if (SearchNamespaces) {
3973 TmpRes.suppressDiagnostics();
3974 for (llvm::SmallVector<TypoCorrection,
3975 16>::iterator QRI = QualifiedResults.begin(),
3976 QRIEnd = QualifiedResults.end();
3977 QRI != QRIEnd; ++QRI) {
3978 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
3979 NIEnd = Namespaces.end();
3980 NI != NIEnd; ++NI) {
3981 DeclContext *Ctx = NI->DeclCtx;
3983 // FIXME: Stop searching once the namespaces are too far away to create
3984 // acceptable corrections for this identifier (since the namespaces
3985 // are sorted in ascending order by edit distance).
3988 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
3989 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
3991 // Any corrections added below will be validated in subsequent
3992 // iterations of the main while() loop over the Consumer's contents.
3993 switch (TmpRes.getResultKind()) {
3994 case LookupResult::Found: {
3995 TypoCorrection TC(*QRI);
3996 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3997 TC.setCorrectionSpecifier(NI->NameSpecifier);
3998 TC.setQualifierDistance(NI->EditDistance);
3999 Consumer.addCorrection(TC);
4002 case LookupResult::FoundOverloaded: {
4003 TypoCorrection TC(*QRI);
4004 TC.setCorrectionSpecifier(NI->NameSpecifier);
4005 TC.setQualifierDistance(NI->EditDistance);
4006 for (LookupResult::iterator TRD = TmpRes.begin(),
4007 TRDEnd = TmpRes.end();
4008 TRD != TRDEnd; ++TRD)
4009 TC.addCorrectionDecl(*TRD);
4010 Consumer.addCorrection(TC);
4013 case LookupResult::NotFound:
4014 case LookupResult::NotFoundInCurrentInstantiation:
4015 case LookupResult::Ambiguous:
4016 case LookupResult::FoundUnresolvedValue:
4023 QualifiedResults.clear();
4026 // No corrections remain...
4027 if (Consumer.empty()) return TypoCorrection();
4029 TypoResultsMap &BestResults = Consumer.getBestResults();
4030 ED = Consumer.getBestEditDistance(true);
4032 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
4033 // If this was an unqualified lookup and we believe the callback
4034 // object wouldn't have filtered out possible corrections, note
4035 // that no correction was found.
4036 if (IsUnqualifiedLookup && !ValidatingCallback)
4037 (void)UnqualifiedTyposCorrected[Typo];
4039 return TypoCorrection();
4042 // If only a single name remains, return that result.
4043 if (BestResults.size() == 1) {
4044 const TypoResultList &CorrectionList = BestResults.begin()->second;
4045 const TypoCorrection &Result = CorrectionList.front();
4046 if (CorrectionList.size() != 1) return TypoCorrection();
4048 // Don't correct to a keyword that's the same as the typo; the keyword
4049 // wasn't actually in scope.
4050 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4052 // Record the correction for unqualified lookup.
4053 if (IsUnqualifiedLookup)
4054 UnqualifiedTyposCorrected[Typo] = Result;
4056 TypoCorrection TC = Result;
4057 TC.setCorrectionRange(SS, TypoName);
4060 else if (BestResults.size() > 1
4061 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4062 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4063 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4064 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4065 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
4066 && BestResults["super"].front().isKeyword()) {
4067 // Prefer 'super' when we're completing in a message-receiver
4070 // Don't correct to a keyword that's the same as the typo; the keyword
4071 // wasn't actually in scope.
4072 if (ED == 0) return TypoCorrection();
4074 // Record the correction for unqualified lookup.
4075 if (IsUnqualifiedLookup)
4076 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
4078 TypoCorrection TC = BestResults["super"].front();
4079 TC.setCorrectionRange(SS, TypoName);
4083 // If this was an unqualified lookup and we believe the callback object did
4084 // not filter out possible corrections, note that no correction was found.
4085 if (IsUnqualifiedLookup && !ValidatingCallback)
4086 (void)UnqualifiedTyposCorrected[Typo];
4088 return TypoCorrection();
4091 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4095 CorrectionDecls.clear();
4097 CorrectionDecls.push_back(CDecl);
4099 if (!CorrectionName)
4100 CorrectionName = CDecl->getDeclName();
4103 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4104 if (CorrectionNameSpec) {
4105 std::string tmpBuffer;
4106 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4107 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4108 CorrectionName.printName(PrefixOStream);
4109 return PrefixOStream.str();
4112 return CorrectionName.getAsString();