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/Lookup.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclLookups.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/Basic/Builtins.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Sema/DeclSpec.h"
27 #include "clang/Sema/ExternalSemaSource.h"
28 #include "clang/Sema/Overload.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "clang/Sema/Sema.h"
32 #include "clang/Sema/SemaInternal.h"
33 #include "clang/Sema/TemplateDeduction.h"
34 #include "clang/Sema/TypoCorrection.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SetVector.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 (!isForRedeclaration()) {
291 // If we're looking for one of the allocation or deallocation
292 // operators, make sure that the implicitly-declared new and delete
293 // operators can be found.
294 switch (NameInfo.getName().getCXXOverloadedOperator()) {
298 case OO_Array_Delete:
299 SemaRef.DeclareGlobalNewDelete();
306 // Compiler builtins are always visible, regardless of where they end
307 // up being declared.
308 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
309 if (unsigned BuiltinID = Id->getBuiltinID()) {
310 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
317 void LookupResult::sanityImpl() const {
318 // Note that this function is never called by NDEBUG builds. See
319 // LookupResult::sanity().
320 assert(ResultKind != NotFound || Decls.size() == 0);
321 assert(ResultKind != Found || Decls.size() == 1);
322 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
323 (Decls.size() == 1 &&
324 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
325 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
326 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
327 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
328 Ambiguity == AmbiguousBaseSubobjectTypes)));
329 assert((Paths != NULL) == (ResultKind == Ambiguous &&
330 (Ambiguity == AmbiguousBaseSubobjectTypes ||
331 Ambiguity == AmbiguousBaseSubobjects)));
334 // Necessary because CXXBasePaths is not complete in Sema.h
335 void LookupResult::deletePaths(CXXBasePaths *Paths) {
339 static NamedDecl *getVisibleDecl(NamedDecl *D);
341 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
342 return getVisibleDecl(D);
345 /// Resolves the result kind of this lookup.
346 void LookupResult::resolveKind() {
347 unsigned N = Decls.size();
349 // Fast case: no possible ambiguity.
351 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
355 // If there's a single decl, we need to examine it to decide what
356 // kind of lookup this is.
358 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
359 if (isa<FunctionTemplateDecl>(D))
360 ResultKind = FoundOverloaded;
361 else if (isa<UnresolvedUsingValueDecl>(D))
362 ResultKind = FoundUnresolvedValue;
366 // Don't do any extra resolution if we've already resolved as ambiguous.
367 if (ResultKind == Ambiguous) return;
369 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
370 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
372 bool Ambiguous = false;
373 bool HasTag = false, HasFunction = false, HasNonFunction = false;
374 bool HasFunctionTemplate = false, HasUnresolved = false;
376 unsigned UniqueTagIndex = 0;
380 NamedDecl *D = Decls[I]->getUnderlyingDecl();
381 D = cast<NamedDecl>(D->getCanonicalDecl());
383 // Ignore an invalid declaration unless it's the only one left.
384 if (D->isInvalidDecl() && I < N-1) {
385 Decls[I] = Decls[--N];
389 // Redeclarations of types via typedef can occur both within a scope
390 // and, through using declarations and directives, across scopes. There is
391 // no ambiguity if they all refer to the same type, so unique based on the
393 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
394 if (!TD->getDeclContext()->isRecord()) {
395 QualType T = SemaRef.Context.getTypeDeclType(TD);
396 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
397 // The type is not unique; pull something off the back and continue
399 Decls[I] = Decls[--N];
405 if (!Unique.insert(D)) {
406 // If it's not unique, pull something off the back (and
407 // continue at this index).
408 Decls[I] = Decls[--N];
412 // Otherwise, do some decl type analysis and then continue.
414 if (isa<UnresolvedUsingValueDecl>(D)) {
415 HasUnresolved = true;
416 } else if (isa<TagDecl>(D)) {
421 } else if (isa<FunctionTemplateDecl>(D)) {
423 HasFunctionTemplate = true;
424 } else if (isa<FunctionDecl>(D)) {
429 HasNonFunction = true;
434 // C++ [basic.scope.hiding]p2:
435 // A class name or enumeration name can be hidden by the name of
436 // an object, function, or enumerator declared in the same
437 // scope. If a class or enumeration name and an object, function,
438 // or enumerator are declared in the same scope (in any order)
439 // with the same name, the class or enumeration name is hidden
440 // wherever the object, function, or enumerator name is visible.
441 // But it's still an error if there are distinct tag types found,
442 // even if they're not visible. (ref?)
443 if (HideTags && HasTag && !Ambiguous &&
444 (HasFunction || HasNonFunction || HasUnresolved)) {
445 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
446 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
447 Decls[UniqueTagIndex] = Decls[--N];
454 if (HasNonFunction && (HasFunction || HasUnresolved))
458 setAmbiguous(LookupResult::AmbiguousReference);
459 else if (HasUnresolved)
460 ResultKind = LookupResult::FoundUnresolvedValue;
461 else if (N > 1 || HasFunctionTemplate)
462 ResultKind = LookupResult::FoundOverloaded;
464 ResultKind = LookupResult::Found;
467 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
468 CXXBasePaths::const_paths_iterator I, E;
469 for (I = P.begin(), E = P.end(); I != E; ++I)
470 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
471 DE = I->Decls.end(); DI != DE; ++DI)
475 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
476 Paths = new CXXBasePaths;
478 addDeclsFromBasePaths(*Paths);
480 setAmbiguous(AmbiguousBaseSubobjects);
483 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
484 Paths = new CXXBasePaths;
486 addDeclsFromBasePaths(*Paths);
488 setAmbiguous(AmbiguousBaseSubobjectTypes);
491 void LookupResult::print(raw_ostream &Out) {
492 Out << Decls.size() << " result(s)";
493 if (isAmbiguous()) Out << ", ambiguous";
494 if (Paths) Out << ", base paths present";
496 for (iterator I = begin(), E = end(); I != E; ++I) {
502 /// \brief Lookup a builtin function, when name lookup would otherwise
504 static bool LookupBuiltin(Sema &S, LookupResult &R) {
505 Sema::LookupNameKind NameKind = R.getLookupKind();
507 // If we didn't find a use of this identifier, and if the identifier
508 // corresponds to a compiler builtin, create the decl object for the builtin
509 // now, injecting it into translation unit scope, and return it.
510 if (NameKind == Sema::LookupOrdinaryName ||
511 NameKind == Sema::LookupRedeclarationWithLinkage) {
512 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
514 // If this is a builtin on this (or all) targets, create the decl.
515 if (unsigned BuiltinID = II->getBuiltinID()) {
516 // In C++, we don't have any predefined library functions like
517 // 'malloc'. Instead, we'll just error.
518 if (S.getLangOpts().CPlusPlus &&
519 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
522 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
523 BuiltinID, S.TUScope,
524 R.isForRedeclaration(),
530 if (R.isForRedeclaration()) {
531 // If we're redeclaring this function anyway, forget that
532 // this was a builtin at all.
533 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
544 /// \brief Determine whether we can declare a special member function within
545 /// the class at this point.
546 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
547 // We need to have a definition for the class.
548 if (!Class->getDefinition() || Class->isDependentContext())
551 // We can't be in the middle of defining the class.
552 return !Class->isBeingDefined();
555 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
556 if (!CanDeclareSpecialMemberFunction(Class))
559 // If the default constructor has not yet been declared, do so now.
560 if (Class->needsImplicitDefaultConstructor())
561 DeclareImplicitDefaultConstructor(Class);
563 // If the copy constructor has not yet been declared, do so now.
564 if (Class->needsImplicitCopyConstructor())
565 DeclareImplicitCopyConstructor(Class);
567 // If the copy assignment operator has not yet been declared, do so now.
568 if (Class->needsImplicitCopyAssignment())
569 DeclareImplicitCopyAssignment(Class);
571 if (getLangOpts().CPlusPlus11) {
572 // If the move constructor has not yet been declared, do so now.
573 if (Class->needsImplicitMoveConstructor())
574 DeclareImplicitMoveConstructor(Class); // might not actually do it
576 // If the move assignment operator has not yet been declared, do so now.
577 if (Class->needsImplicitMoveAssignment())
578 DeclareImplicitMoveAssignment(Class); // might not actually do it
581 // If the destructor has not yet been declared, do so now.
582 if (Class->needsImplicitDestructor())
583 DeclareImplicitDestructor(Class);
586 /// \brief Determine whether this is the name of an implicitly-declared
587 /// special member function.
588 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
589 switch (Name.getNameKind()) {
590 case DeclarationName::CXXConstructorName:
591 case DeclarationName::CXXDestructorName:
594 case DeclarationName::CXXOperatorName:
595 return Name.getCXXOverloadedOperator() == OO_Equal;
604 /// \brief If there are any implicit member functions with the given name
605 /// that need to be declared in the given declaration context, do so.
606 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
607 DeclarationName Name,
608 const DeclContext *DC) {
612 switch (Name.getNameKind()) {
613 case DeclarationName::CXXConstructorName:
614 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
615 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
616 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
617 if (Record->needsImplicitDefaultConstructor())
618 S.DeclareImplicitDefaultConstructor(Class);
619 if (Record->needsImplicitCopyConstructor())
620 S.DeclareImplicitCopyConstructor(Class);
621 if (S.getLangOpts().CPlusPlus11 &&
622 Record->needsImplicitMoveConstructor())
623 S.DeclareImplicitMoveConstructor(Class);
627 case DeclarationName::CXXDestructorName:
628 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
629 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
630 CanDeclareSpecialMemberFunction(Record))
631 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
634 case DeclarationName::CXXOperatorName:
635 if (Name.getCXXOverloadedOperator() != OO_Equal)
638 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
639 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
640 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
641 if (Record->needsImplicitCopyAssignment())
642 S.DeclareImplicitCopyAssignment(Class);
643 if (S.getLangOpts().CPlusPlus11 &&
644 Record->needsImplicitMoveAssignment())
645 S.DeclareImplicitMoveAssignment(Class);
655 // Adds all qualifying matches for a name within a decl context to the
656 // given lookup result. Returns true if any matches were found.
657 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
660 // Lazily declare C++ special member functions.
661 if (S.getLangOpts().CPlusPlus)
662 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
664 // Perform lookup into this declaration context.
665 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
666 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
669 if ((D = R.getAcceptableDecl(D))) {
675 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
678 if (R.getLookupName().getNameKind()
679 != DeclarationName::CXXConversionFunctionName ||
680 R.getLookupName().getCXXNameType()->isDependentType() ||
681 !isa<CXXRecordDecl>(DC))
685 // A specialization of a conversion function template is not found by
686 // name lookup. Instead, any conversion function templates visible in the
687 // context of the use are considered. [...]
688 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
689 if (!Record->isCompleteDefinition())
692 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
693 UEnd = Record->conversion_end(); U != UEnd; ++U) {
694 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
698 // When we're performing lookup for the purposes of redeclaration, just
699 // add the conversion function template. When we deduce template
700 // arguments for specializations, we'll end up unifying the return
701 // type of the new declaration with the type of the function template.
702 if (R.isForRedeclaration()) {
703 R.addDecl(ConvTemplate);
709 // [...] For each such operator, if argument deduction succeeds
710 // (14.9.2.3), the resulting specialization is used as if found by
713 // When referencing a conversion function for any purpose other than
714 // a redeclaration (such that we'll be building an expression with the
715 // result), perform template argument deduction and place the
716 // specialization into the result set. We do this to avoid forcing all
717 // callers to perform special deduction for conversion functions.
718 TemplateDeductionInfo Info(R.getNameLoc());
719 FunctionDecl *Specialization = 0;
721 const FunctionProtoType *ConvProto
722 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
723 assert(ConvProto && "Nonsensical conversion function template type");
725 // Compute the type of the function that we would expect the conversion
726 // function to have, if it were to match the name given.
727 // FIXME: Calling convention!
728 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
729 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_Default);
730 EPI.ExceptionSpecType = EST_None;
731 EPI.NumExceptions = 0;
732 QualType ExpectedType
733 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
734 ArrayRef<QualType>(), EPI);
736 // Perform template argument deduction against the type that we would
737 // expect the function to have.
738 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
739 Specialization, Info)
740 == Sema::TDK_Success) {
741 R.addDecl(Specialization);
749 // Performs C++ unqualified lookup into the given file context.
751 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
752 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
754 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
756 // Perform direct name lookup into the LookupCtx.
757 bool Found = LookupDirect(S, R, NS);
759 // Perform direct name lookup into the namespaces nominated by the
760 // using directives whose common ancestor is this namespace.
761 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
762 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
764 for (; UI != UEnd; ++UI)
765 if (LookupDirect(S, R, UI->getNominatedNamespace()))
773 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
774 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
775 return Ctx->isFileContext();
779 // Find the next outer declaration context from this scope. This
780 // routine actually returns the semantic outer context, which may
781 // differ from the lexical context (encoded directly in the Scope
782 // stack) when we are parsing a member of a class template. In this
783 // case, the second element of the pair will be true, to indicate that
784 // name lookup should continue searching in this semantic context when
785 // it leaves the current template parameter scope.
786 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
787 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
788 DeclContext *Lexical = 0;
789 for (Scope *OuterS = S->getParent(); OuterS;
790 OuterS = OuterS->getParent()) {
791 if (OuterS->getEntity()) {
792 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
797 // C++ [temp.local]p8:
798 // In the definition of a member of a class template that appears
799 // outside of the namespace containing the class template
800 // definition, the name of a template-parameter hides the name of
801 // a member of this namespace.
808 // template<class T> class B {
813 // template<class C> void N::B<C>::f(C) {
814 // C b; // C is the template parameter, not N::C
817 // In this example, the lexical context we return is the
818 // TranslationUnit, while the semantic context is the namespace N.
819 if (!Lexical || !DC || !S->getParent() ||
820 !S->getParent()->isTemplateParamScope())
821 return std::make_pair(Lexical, false);
823 // Find the outermost template parameter scope.
824 // For the example, this is the scope for the template parameters of
825 // template<class C>.
826 Scope *OutermostTemplateScope = S->getParent();
827 while (OutermostTemplateScope->getParent() &&
828 OutermostTemplateScope->getParent()->isTemplateParamScope())
829 OutermostTemplateScope = OutermostTemplateScope->getParent();
831 // Find the namespace context in which the original scope occurs. In
832 // the example, this is namespace N.
833 DeclContext *Semantic = DC;
834 while (!Semantic->isFileContext())
835 Semantic = Semantic->getParent();
837 // Find the declaration context just outside of the template
838 // parameter scope. This is the context in which the template is
839 // being lexically declaration (a namespace context). In the
840 // example, this is the global scope.
841 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
842 Lexical->Encloses(Semantic))
843 return std::make_pair(Semantic, true);
845 return std::make_pair(Lexical, false);
848 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
849 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
851 DeclarationName Name = R.getLookupName();
853 // If this is the name of an implicitly-declared special member function,
854 // go through the scope stack to implicitly declare
855 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
856 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
857 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
858 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
861 // Implicitly declare member functions with the name we're looking for, if in
862 // fact we are in a scope where it matters.
865 IdentifierResolver::iterator
866 I = IdResolver.begin(Name),
867 IEnd = IdResolver.end();
869 // First we lookup local scope.
870 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
871 // ...During unqualified name lookup (3.4.1), the names appear as if
872 // they were declared in the nearest enclosing namespace which contains
873 // both the using-directive and the nominated namespace.
874 // [Note: in this context, "contains" means "contains directly or
878 // namespace A { int i; }
882 // using namespace A;
883 // ++i; // finds local 'i', A::i appears at global scope
887 DeclContext *OutsideOfTemplateParamDC = 0;
888 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
889 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
891 // Check whether the IdResolver has anything in this scope.
893 for (; I != IEnd && S->isDeclScope(*I); ++I) {
894 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
901 if (S->isClassScope())
902 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
903 R.setNamingClass(Record);
907 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
908 S->getParent() && !S->getParent()->isTemplateParamScope()) {
909 // We've just searched the last template parameter scope and
910 // found nothing, so look into the contexts between the
911 // lexical and semantic declaration contexts returned by
912 // findOuterContext(). This implements the name lookup behavior
913 // of C++ [temp.local]p8.
914 Ctx = OutsideOfTemplateParamDC;
915 OutsideOfTemplateParamDC = 0;
919 DeclContext *OuterCtx;
920 bool SearchAfterTemplateScope;
921 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
922 if (SearchAfterTemplateScope)
923 OutsideOfTemplateParamDC = OuterCtx;
925 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
926 // We do not directly look into transparent contexts, since
927 // those entities will be found in the nearest enclosing
928 // non-transparent context.
929 if (Ctx->isTransparentContext())
932 // We do not look directly into function or method contexts,
933 // since all of the local variables and parameters of the
934 // function/method are present within the Scope.
935 if (Ctx->isFunctionOrMethod()) {
936 // If we have an Objective-C instance method, look for ivars
937 // in the corresponding interface.
938 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
939 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
940 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
941 ObjCInterfaceDecl *ClassDeclared;
942 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
943 Name.getAsIdentifierInfo(),
945 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
957 // If this is a file context, we need to perform unqualified name
958 // lookup considering using directives.
959 if (Ctx->isFileContext()) {
960 UnqualUsingDirectiveSet UDirs;
961 UDirs.visit(Ctx, Ctx);
964 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
972 // Perform qualified name lookup into this context.
973 // FIXME: In some cases, we know that every name that could be found by
974 // this qualified name lookup will also be on the identifier chain. For
975 // example, inside a class without any base classes, we never need to
976 // perform qualified lookup because all of the members are on top of the
978 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
984 // Stop if we ran out of scopes.
985 // FIXME: This really, really shouldn't be happening.
986 if (!S) return false;
988 // If we are looking for members, no need to look into global/namespace scope.
989 if (R.getLookupKind() == LookupMemberName)
992 // Collect UsingDirectiveDecls in all scopes, and recursively all
993 // nominated namespaces by those using-directives.
995 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
996 // don't build it for each lookup!
998 UnqualUsingDirectiveSet UDirs;
999 UDirs.visitScopeChain(Initial, S);
1002 // Lookup namespace scope, and global scope.
1003 // Unqualified name lookup in C++ requires looking into scopes
1004 // that aren't strictly lexical, and therefore we walk through the
1005 // context as well as walking through the scopes.
1006 for (; S; S = S->getParent()) {
1007 // Check whether the IdResolver has anything in this scope.
1009 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1010 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1011 // We found something. Look for anything else in our scope
1012 // with this same name and in an acceptable identifier
1013 // namespace, so that we can construct an overload set if we
1020 if (Found && S->isTemplateParamScope()) {
1025 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1026 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1027 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1028 // We've just searched the last template parameter scope and
1029 // found nothing, so look into the contexts between the
1030 // lexical and semantic declaration contexts returned by
1031 // findOuterContext(). This implements the name lookup behavior
1032 // of C++ [temp.local]p8.
1033 Ctx = OutsideOfTemplateParamDC;
1034 OutsideOfTemplateParamDC = 0;
1038 DeclContext *OuterCtx;
1039 bool SearchAfterTemplateScope;
1040 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1041 if (SearchAfterTemplateScope)
1042 OutsideOfTemplateParamDC = OuterCtx;
1044 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1045 // We do not directly look into transparent contexts, since
1046 // those entities will be found in the nearest enclosing
1047 // non-transparent context.
1048 if (Ctx->isTransparentContext())
1051 // If we have a context, and it's not a context stashed in the
1052 // template parameter scope for an out-of-line definition, also
1053 // look into that context.
1054 if (!(Found && S && S->isTemplateParamScope())) {
1055 assert(Ctx->isFileContext() &&
1056 "We should have been looking only at file context here already.");
1058 // Look into context considering using-directives.
1059 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1068 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1073 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1080 /// \brief Retrieve the visible declaration corresponding to D, if any.
1082 /// This routine determines whether the declaration D is visible in the current
1083 /// module, with the current imports. If not, it checks whether any
1084 /// redeclaration of D is visible, and if so, returns that declaration.
1086 /// \returns D, or a visible previous declaration of D, whichever is more recent
1087 /// and visible. If no declaration of D is visible, returns null.
1088 static NamedDecl *getVisibleDecl(NamedDecl *D) {
1089 if (LookupResult::isVisible(D))
1092 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1093 RD != RDEnd; ++RD) {
1094 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1095 if (LookupResult::isVisible(ND))
1103 /// @brief Perform unqualified name lookup starting from a given
1106 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1107 /// used to find names within the current scope. For example, 'x' in
1111 /// return x; // unqualified name look finds 'x' in the global scope
1115 /// Different lookup criteria can find different names. For example, a
1116 /// particular scope can have both a struct and a function of the same
1117 /// name, and each can be found by certain lookup criteria. For more
1118 /// information about lookup criteria, see the documentation for the
1119 /// class LookupCriteria.
1121 /// @param S The scope from which unqualified name lookup will
1122 /// begin. If the lookup criteria permits, name lookup may also search
1123 /// in the parent scopes.
1125 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1126 /// look up and the lookup kind), and is updated with the results of lookup
1127 /// including zero or more declarations and possibly additional information
1128 /// used to diagnose ambiguities.
1130 /// @returns \c true if lookup succeeded and false otherwise.
1131 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1132 DeclarationName Name = R.getLookupName();
1133 if (!Name) return false;
1135 LookupNameKind NameKind = R.getLookupKind();
1137 if (!getLangOpts().CPlusPlus) {
1138 // Unqualified name lookup in C/Objective-C is purely lexical, so
1139 // search in the declarations attached to the name.
1140 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1141 // Find the nearest non-transparent declaration scope.
1142 while (!(S->getFlags() & Scope::DeclScope) ||
1144 static_cast<DeclContext *>(S->getEntity())
1145 ->isTransparentContext()))
1149 unsigned IDNS = R.getIdentifierNamespace();
1151 // Scan up the scope chain looking for a decl that matches this
1152 // identifier that is in the appropriate namespace. This search
1153 // should not take long, as shadowing of names is uncommon, and
1154 // deep shadowing is extremely uncommon.
1155 bool LeftStartingScope = false;
1157 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1158 IEnd = IdResolver.end();
1160 if ((*I)->isInIdentifierNamespace(IDNS)) {
1161 if (NameKind == LookupRedeclarationWithLinkage) {
1162 // Determine whether this (or a previous) declaration is
1164 if (!LeftStartingScope && !S->isDeclScope(*I))
1165 LeftStartingScope = true;
1167 // If we found something outside of our starting scope that
1168 // does not have linkage, skip it.
1169 if (LeftStartingScope && !((*I)->hasLinkage()))
1172 else if (NameKind == LookupObjCImplicitSelfParam &&
1173 !isa<ImplicitParamDecl>(*I))
1176 // If this declaration is module-private and it came from an AST
1177 // file, we can't see it.
1178 NamedDecl *D = R.isHiddenDeclarationVisible()? *I : getVisibleDecl(*I);
1184 // Check whether there are any other declarations with the same name
1185 // and in the same scope.
1187 // Find the scope in which this declaration was declared (if it
1188 // actually exists in a Scope).
1189 while (S && !S->isDeclScope(D))
1192 // If the scope containing the declaration is the translation unit,
1193 // then we'll need to perform our checks based on the matching
1194 // DeclContexts rather than matching scopes.
1195 if (S && isNamespaceOrTranslationUnitScope(S))
1198 // Compute the DeclContext, if we need it.
1199 DeclContext *DC = 0;
1201 DC = (*I)->getDeclContext()->getRedeclContext();
1203 IdentifierResolver::iterator LastI = I;
1204 for (++LastI; LastI != IEnd; ++LastI) {
1206 // Match based on scope.
1207 if (!S->isDeclScope(*LastI))
1210 // Match based on DeclContext.
1212 = (*LastI)->getDeclContext()->getRedeclContext();
1213 if (!LastDC->Equals(DC))
1217 // If the declaration isn't in the right namespace, skip it.
1218 if (!(*LastI)->isInIdentifierNamespace(IDNS))
1221 D = R.isHiddenDeclarationVisible()? *LastI : getVisibleDecl(*LastI);
1231 // Perform C++ unqualified name lookup.
1232 if (CppLookupName(R, S))
1236 // If we didn't find a use of this identifier, and if the identifier
1237 // corresponds to a compiler builtin, create the decl object for the builtin
1238 // now, injecting it into translation unit scope, and return it.
1239 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1242 // If we didn't find a use of this identifier, the ExternalSource
1243 // may be able to handle the situation.
1244 // Note: some lookup failures are expected!
1245 // See e.g. R.isForRedeclaration().
1246 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1249 /// @brief Perform qualified name lookup in the namespaces nominated by
1250 /// using directives by the given context.
1252 /// C++98 [namespace.qual]p2:
1253 /// Given X::m (where X is a user-declared namespace), or given \::m
1254 /// (where X is the global namespace), let S be the set of all
1255 /// declarations of m in X and in the transitive closure of all
1256 /// namespaces nominated by using-directives in X and its used
1257 /// namespaces, except that using-directives are ignored in any
1258 /// namespace, including X, directly containing one or more
1259 /// declarations of m. No namespace is searched more than once in
1260 /// the lookup of a name. If S is the empty set, the program is
1261 /// ill-formed. Otherwise, if S has exactly one member, or if the
1262 /// context of the reference is a using-declaration
1263 /// (namespace.udecl), S is the required set of declarations of
1264 /// m. Otherwise if the use of m is not one that allows a unique
1265 /// declaration to be chosen from S, the program is ill-formed.
1267 /// C++98 [namespace.qual]p5:
1268 /// During the lookup of a qualified namespace member name, if the
1269 /// lookup finds more than one declaration of the member, and if one
1270 /// declaration introduces a class name or enumeration name and the
1271 /// other declarations either introduce the same object, the same
1272 /// enumerator or a set of functions, the non-type name hides the
1273 /// class or enumeration name if and only if the declarations are
1274 /// from the same namespace; otherwise (the declarations are from
1275 /// different namespaces), the program is ill-formed.
1276 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1277 DeclContext *StartDC) {
1278 assert(StartDC->isFileContext() && "start context is not a file context");
1280 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1281 DeclContext::udir_iterator E = StartDC->using_directives_end();
1283 if (I == E) return false;
1285 // We have at least added all these contexts to the queue.
1286 llvm::SmallPtrSet<DeclContext*, 8> Visited;
1287 Visited.insert(StartDC);
1289 // We have not yet looked into these namespaces, much less added
1290 // their "using-children" to the queue.
1291 SmallVector<NamespaceDecl*, 8> Queue;
1293 // We have already looked into the initial namespace; seed the queue
1294 // with its using-children.
1295 for (; I != E; ++I) {
1296 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1297 if (Visited.insert(ND))
1298 Queue.push_back(ND);
1301 // The easiest way to implement the restriction in [namespace.qual]p5
1302 // is to check whether any of the individual results found a tag
1303 // and, if so, to declare an ambiguity if the final result is not
1305 bool FoundTag = false;
1306 bool FoundNonTag = false;
1308 LookupResult LocalR(LookupResult::Temporary, R);
1311 while (!Queue.empty()) {
1312 NamespaceDecl *ND = Queue.back();
1315 // We go through some convolutions here to avoid copying results
1316 // between LookupResults.
1317 bool UseLocal = !R.empty();
1318 LookupResult &DirectR = UseLocal ? LocalR : R;
1319 bool FoundDirect = LookupDirect(S, DirectR, ND);
1322 // First do any local hiding.
1323 DirectR.resolveKind();
1325 // If the local result is a tag, remember that.
1326 if (DirectR.isSingleTagDecl())
1331 // Append the local results to the total results if necessary.
1333 R.addAllDecls(LocalR);
1338 // If we find names in this namespace, ignore its using directives.
1344 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1345 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1346 if (Visited.insert(Nom))
1347 Queue.push_back(Nom);
1352 if (FoundTag && FoundNonTag)
1353 R.setAmbiguousQualifiedTagHiding();
1361 /// \brief Callback that looks for any member of a class with the given name.
1362 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1365 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1367 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1368 Path.Decls = BaseRecord->lookup(N);
1369 return !Path.Decls.empty();
1372 /// \brief Determine whether the given set of member declarations contains only
1373 /// static members, nested types, and enumerators.
1374 template<typename InputIterator>
1375 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1376 Decl *D = (*First)->getUnderlyingDecl();
1377 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1380 if (isa<CXXMethodDecl>(D)) {
1381 // Determine whether all of the methods are static.
1382 bool AllMethodsAreStatic = true;
1383 for(; First != Last; ++First) {
1384 D = (*First)->getUnderlyingDecl();
1386 if (!isa<CXXMethodDecl>(D)) {
1387 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1391 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1392 AllMethodsAreStatic = false;
1397 if (AllMethodsAreStatic)
1404 /// \brief Perform qualified name lookup into a given context.
1406 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1407 /// names when the context of those names is explicit specified, e.g.,
1408 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1410 /// Different lookup criteria can find different names. For example, a
1411 /// particular scope can have both a struct and a function of the same
1412 /// name, and each can be found by certain lookup criteria. For more
1413 /// information about lookup criteria, see the documentation for the
1414 /// class LookupCriteria.
1416 /// \param R captures both the lookup criteria and any lookup results found.
1418 /// \param LookupCtx The context in which qualified name lookup will
1419 /// search. If the lookup criteria permits, name lookup may also search
1420 /// in the parent contexts or (for C++ classes) base classes.
1422 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1423 /// occurs as part of unqualified name lookup.
1425 /// \returns true if lookup succeeded, false if it failed.
1426 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1427 bool InUnqualifiedLookup) {
1428 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1430 if (!R.getLookupName())
1433 // Make sure that the declaration context is complete.
1434 assert((!isa<TagDecl>(LookupCtx) ||
1435 LookupCtx->isDependentContext() ||
1436 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
1437 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
1438 "Declaration context must already be complete!");
1440 // Perform qualified name lookup into the LookupCtx.
1441 if (LookupDirect(*this, R, LookupCtx)) {
1443 if (isa<CXXRecordDecl>(LookupCtx))
1444 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1448 // Don't descend into implied contexts for redeclarations.
1449 // C++98 [namespace.qual]p6:
1450 // In a declaration for a namespace member in which the
1451 // declarator-id is a qualified-id, given that the qualified-id
1452 // for the namespace member has the form
1453 // nested-name-specifier unqualified-id
1454 // the unqualified-id shall name a member of the namespace
1455 // designated by the nested-name-specifier.
1456 // See also [class.mfct]p5 and [class.static.data]p2.
1457 if (R.isForRedeclaration())
1460 // If this is a namespace, look it up in the implied namespaces.
1461 if (LookupCtx->isFileContext())
1462 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1464 // If this isn't a C++ class, we aren't allowed to look into base
1465 // classes, we're done.
1466 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1467 if (!LookupRec || !LookupRec->getDefinition())
1470 // If we're performing qualified name lookup into a dependent class,
1471 // then we are actually looking into a current instantiation. If we have any
1472 // dependent base classes, then we either have to delay lookup until
1473 // template instantiation time (at which point all bases will be available)
1474 // or we have to fail.
1475 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1476 LookupRec->hasAnyDependentBases()) {
1477 R.setNotFoundInCurrentInstantiation();
1481 // Perform lookup into our base classes.
1483 Paths.setOrigin(LookupRec);
1485 // Look for this member in our base classes
1486 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1487 switch (R.getLookupKind()) {
1488 case LookupObjCImplicitSelfParam:
1489 case LookupOrdinaryName:
1490 case LookupMemberName:
1491 case LookupRedeclarationWithLinkage:
1492 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1496 BaseCallback = &CXXRecordDecl::FindTagMember;
1500 BaseCallback = &LookupAnyMember;
1503 case LookupUsingDeclName:
1504 // This lookup is for redeclarations only.
1506 case LookupOperatorName:
1507 case LookupNamespaceName:
1508 case LookupObjCProtocolName:
1510 // These lookups will never find a member in a C++ class (or base class).
1513 case LookupNestedNameSpecifierName:
1514 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1518 if (!LookupRec->lookupInBases(BaseCallback,
1519 R.getLookupName().getAsOpaquePtr(), Paths))
1522 R.setNamingClass(LookupRec);
1524 // C++ [class.member.lookup]p2:
1525 // [...] If the resulting set of declarations are not all from
1526 // sub-objects of the same type, or the set has a nonstatic member
1527 // and includes members from distinct sub-objects, there is an
1528 // ambiguity and the program is ill-formed. Otherwise that set is
1529 // the result of the lookup.
1530 QualType SubobjectType;
1531 int SubobjectNumber = 0;
1532 AccessSpecifier SubobjectAccess = AS_none;
1534 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1535 Path != PathEnd; ++Path) {
1536 const CXXBasePathElement &PathElement = Path->back();
1538 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1539 // across all paths.
1540 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1542 // Determine whether we're looking at a distinct sub-object or not.
1543 if (SubobjectType.isNull()) {
1544 // This is the first subobject we've looked at. Record its type.
1545 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1546 SubobjectNumber = PathElement.SubobjectNumber;
1551 != Context.getCanonicalType(PathElement.Base->getType())) {
1552 // We found members of the given name in two subobjects of
1553 // different types. If the declaration sets aren't the same, this
1554 // this lookup is ambiguous.
1555 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
1556 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1557 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1558 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
1560 while (FirstD != FirstPath->Decls.end() &&
1561 CurrentD != Path->Decls.end()) {
1562 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1563 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1570 if (FirstD == FirstPath->Decls.end() &&
1571 CurrentD == Path->Decls.end())
1575 R.setAmbiguousBaseSubobjectTypes(Paths);
1579 if (SubobjectNumber != PathElement.SubobjectNumber) {
1580 // We have a different subobject of the same type.
1582 // C++ [class.member.lookup]p5:
1583 // A static member, a nested type or an enumerator defined in
1584 // a base class T can unambiguously be found even if an object
1585 // has more than one base class subobject of type T.
1586 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
1589 // We have found a nonstatic member name in multiple, distinct
1590 // subobjects. Name lookup is ambiguous.
1591 R.setAmbiguousBaseSubobjects(Paths);
1596 // Lookup in a base class succeeded; return these results.
1598 DeclContext::lookup_result DR = Paths.front().Decls;
1599 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
1601 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1609 /// @brief Performs name lookup for a name that was parsed in the
1610 /// source code, and may contain a C++ scope specifier.
1612 /// This routine is a convenience routine meant to be called from
1613 /// contexts that receive a name and an optional C++ scope specifier
1614 /// (e.g., "N::M::x"). It will then perform either qualified or
1615 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1616 /// respectively) on the given name and return those results.
1618 /// @param S The scope from which unqualified name lookup will
1621 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1623 /// @param EnteringContext Indicates whether we are going to enter the
1624 /// context of the scope-specifier SS (if present).
1626 /// @returns True if any decls were found (but possibly ambiguous)
1627 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1628 bool AllowBuiltinCreation, bool EnteringContext) {
1629 if (SS && SS->isInvalid()) {
1630 // When the scope specifier is invalid, don't even look for
1635 if (SS && SS->isSet()) {
1636 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1637 // We have resolved the scope specifier to a particular declaration
1638 // contex, and will perform name lookup in that context.
1639 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1642 R.setContextRange(SS->getRange());
1643 return LookupQualifiedName(R, DC);
1646 // We could not resolve the scope specified to a specific declaration
1647 // context, which means that SS refers to an unknown specialization.
1648 // Name lookup can't find anything in this case.
1649 R.setNotFoundInCurrentInstantiation();
1650 R.setContextRange(SS->getRange());
1654 // Perform unqualified name lookup starting in the given scope.
1655 return LookupName(R, S, AllowBuiltinCreation);
1659 /// \brief Produce a diagnostic describing the ambiguity that resulted
1660 /// from name lookup.
1662 /// \param Result The result of the ambiguous lookup to be diagnosed.
1665 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1666 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1668 DeclarationName Name = Result.getLookupName();
1669 SourceLocation NameLoc = Result.getNameLoc();
1670 SourceRange LookupRange = Result.getContextRange();
1672 switch (Result.getAmbiguityKind()) {
1673 case LookupResult::AmbiguousBaseSubobjects: {
1674 CXXBasePaths *Paths = Result.getBasePaths();
1675 QualType SubobjectType = Paths->front().back().Base->getType();
1676 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1677 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1680 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
1681 while (isa<CXXMethodDecl>(*Found) &&
1682 cast<CXXMethodDecl>(*Found)->isStatic())
1685 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1690 case LookupResult::AmbiguousBaseSubobjectTypes: {
1691 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1692 << Name << LookupRange;
1694 CXXBasePaths *Paths = Result.getBasePaths();
1695 std::set<Decl *> DeclsPrinted;
1696 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1697 PathEnd = Paths->end();
1698 Path != PathEnd; ++Path) {
1699 Decl *D = Path->Decls.front();
1700 if (DeclsPrinted.insert(D).second)
1701 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1707 case LookupResult::AmbiguousTagHiding: {
1708 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1710 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1712 LookupResult::iterator DI, DE = Result.end();
1713 for (DI = Result.begin(); DI != DE; ++DI)
1714 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1715 TagDecls.insert(TD);
1716 Diag(TD->getLocation(), diag::note_hidden_tag);
1719 for (DI = Result.begin(); DI != DE; ++DI)
1720 if (!isa<TagDecl>(*DI))
1721 Diag((*DI)->getLocation(), diag::note_hiding_object);
1723 // For recovery purposes, go ahead and implement the hiding.
1724 LookupResult::Filter F = Result.makeFilter();
1725 while (F.hasNext()) {
1726 if (TagDecls.count(F.next()))
1734 case LookupResult::AmbiguousReference: {
1735 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1737 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1738 for (; DI != DE; ++DI)
1739 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1745 llvm_unreachable("unknown ambiguity kind");
1749 struct AssociatedLookup {
1750 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
1751 Sema::AssociatedNamespaceSet &Namespaces,
1752 Sema::AssociatedClassSet &Classes)
1753 : S(S), Namespaces(Namespaces), Classes(Classes),
1754 InstantiationLoc(InstantiationLoc) {
1758 Sema::AssociatedNamespaceSet &Namespaces;
1759 Sema::AssociatedClassSet &Classes;
1760 SourceLocation InstantiationLoc;
1765 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1767 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1769 // Add the associated namespace for this class.
1771 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1772 // be a locally scoped record.
1774 // We skip out of inline namespaces. The innermost non-inline namespace
1775 // contains all names of all its nested inline namespaces anyway, so we can
1776 // replace the entire inline namespace tree with its root.
1777 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1778 Ctx->isInlineNamespace())
1779 Ctx = Ctx->getParent();
1781 if (Ctx->isFileContext())
1782 Namespaces.insert(Ctx->getPrimaryContext());
1785 // \brief Add the associated classes and namespaces for argument-dependent
1786 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1788 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1789 const TemplateArgument &Arg) {
1790 // C++ [basic.lookup.koenig]p2, last bullet:
1792 switch (Arg.getKind()) {
1793 case TemplateArgument::Null:
1796 case TemplateArgument::Type:
1797 // [...] the namespaces and classes associated with the types of the
1798 // template arguments provided for template type parameters (excluding
1799 // template template parameters)
1800 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1803 case TemplateArgument::Template:
1804 case TemplateArgument::TemplateExpansion: {
1805 // [...] the namespaces in which any template template arguments are
1806 // defined; and the classes in which any member templates used as
1807 // template template arguments are defined.
1808 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1809 if (ClassTemplateDecl *ClassTemplate
1810 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1811 DeclContext *Ctx = ClassTemplate->getDeclContext();
1812 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1813 Result.Classes.insert(EnclosingClass);
1814 // Add the associated namespace for this class.
1815 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1820 case TemplateArgument::Declaration:
1821 case TemplateArgument::Integral:
1822 case TemplateArgument::Expression:
1823 case TemplateArgument::NullPtr:
1824 // [Note: non-type template arguments do not contribute to the set of
1825 // associated namespaces. ]
1828 case TemplateArgument::Pack:
1829 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1830 PEnd = Arg.pack_end();
1832 addAssociatedClassesAndNamespaces(Result, *P);
1837 // \brief Add the associated classes and namespaces for
1838 // argument-dependent lookup with an argument of class type
1839 // (C++ [basic.lookup.koenig]p2).
1841 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1842 CXXRecordDecl *Class) {
1844 // Just silently ignore anything whose name is __va_list_tag.
1845 if (Class->getDeclName() == Result.S.VAListTagName)
1848 // C++ [basic.lookup.koenig]p2:
1850 // -- If T is a class type (including unions), its associated
1851 // classes are: the class itself; the class of which it is a
1852 // member, if any; and its direct and indirect base
1853 // classes. Its associated namespaces are the namespaces in
1854 // which its associated classes are defined.
1856 // Add the class of which it is a member, if any.
1857 DeclContext *Ctx = Class->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 // Add the class itself. If we've already seen this class, we don't
1864 // need to visit base classes.
1865 if (!Result.Classes.insert(Class))
1868 // -- If T is a template-id, its associated namespaces and classes are
1869 // the namespace in which the template is defined; for member
1870 // templates, the member template's class; the namespaces and classes
1871 // associated with the types of the template arguments provided for
1872 // template type parameters (excluding template template parameters); the
1873 // namespaces in which any template template arguments are defined; and
1874 // the classes in which any member templates used as template template
1875 // arguments are defined. [Note: non-type template arguments do not
1876 // contribute to the set of associated namespaces. ]
1877 if (ClassTemplateSpecializationDecl *Spec
1878 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1879 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1880 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1881 Result.Classes.insert(EnclosingClass);
1882 // Add the associated namespace for this class.
1883 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1885 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1886 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1887 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
1890 // Only recurse into base classes for complete types.
1891 if (!Class->hasDefinition()) {
1892 QualType type = Result.S.Context.getTypeDeclType(Class);
1893 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
1894 /*no diagnostic*/ 0))
1898 // Add direct and indirect base classes along with their associated
1900 SmallVector<CXXRecordDecl *, 32> Bases;
1901 Bases.push_back(Class);
1902 while (!Bases.empty()) {
1903 // Pop this class off the stack.
1904 Class = Bases.back();
1907 // Visit the base classes.
1908 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1909 BaseEnd = Class->bases_end();
1910 Base != BaseEnd; ++Base) {
1911 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1912 // In dependent contexts, we do ADL twice, and the first time around,
1913 // the base type might be a dependent TemplateSpecializationType, or a
1914 // TemplateTypeParmType. If that happens, simply ignore it.
1915 // FIXME: If we want to support export, we probably need to add the
1916 // namespace of the template in a TemplateSpecializationType, or even
1917 // the classes and namespaces of known non-dependent arguments.
1920 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1921 if (Result.Classes.insert(BaseDecl)) {
1922 // Find the associated namespace for this base class.
1923 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1924 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
1926 // Make sure we visit the bases of this base class.
1927 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1928 Bases.push_back(BaseDecl);
1934 // \brief Add the associated classes and namespaces for
1935 // argument-dependent lookup with an argument of type T
1936 // (C++ [basic.lookup.koenig]p2).
1938 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
1939 // C++ [basic.lookup.koenig]p2:
1941 // For each argument type T in the function call, there is a set
1942 // of zero or more associated namespaces and a set of zero or more
1943 // associated classes to be considered. The sets of namespaces and
1944 // classes is determined entirely by the types of the function
1945 // arguments (and the namespace of any template template
1946 // argument). Typedef names and using-declarations used to specify
1947 // the types do not contribute to this set. The sets of namespaces
1948 // and classes are determined in the following way:
1950 SmallVector<const Type *, 16> Queue;
1951 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1954 switch (T->getTypeClass()) {
1956 #define TYPE(Class, Base)
1957 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1958 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1959 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1960 #define ABSTRACT_TYPE(Class, Base)
1961 #include "clang/AST/TypeNodes.def"
1962 // T is canonical. We can also ignore dependent types because
1963 // we don't need to do ADL at the definition point, but if we
1964 // wanted to implement template export (or if we find some other
1965 // use for associated classes and namespaces...) this would be
1969 // -- If T is a pointer to U or an array of U, its associated
1970 // namespaces and classes are those associated with U.
1972 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1974 case Type::ConstantArray:
1975 case Type::IncompleteArray:
1976 case Type::VariableArray:
1977 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1980 // -- If T is a fundamental type, its associated sets of
1981 // namespaces and classes are both empty.
1985 // -- If T is a class type (including unions), its associated
1986 // classes are: the class itself; the class of which it is a
1987 // member, if any; and its direct and indirect base
1988 // classes. Its associated namespaces are the namespaces in
1989 // which its associated classes are defined.
1990 case Type::Record: {
1991 CXXRecordDecl *Class
1992 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
1993 addAssociatedClassesAndNamespaces(Result, Class);
1997 // -- If T is an enumeration type, its associated namespace is
1998 // the namespace in which it is defined. If it is class
1999 // member, its associated class is the member's class; else
2000 // it has no associated class.
2002 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2004 DeclContext *Ctx = Enum->getDeclContext();
2005 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2006 Result.Classes.insert(EnclosingClass);
2008 // Add the associated namespace for this class.
2009 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2014 // -- If T is a function type, its associated namespaces and
2015 // classes are those associated with the function parameter
2016 // types and those associated with the return type.
2017 case Type::FunctionProto: {
2018 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2019 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2020 ArgEnd = Proto->arg_type_end();
2021 Arg != ArgEnd; ++Arg)
2022 Queue.push_back(Arg->getTypePtr());
2025 case Type::FunctionNoProto: {
2026 const FunctionType *FnType = cast<FunctionType>(T);
2027 T = FnType->getResultType().getTypePtr();
2031 // -- If T is a pointer to a member function of a class X, its
2032 // associated namespaces and classes are those associated
2033 // with the function parameter types and return type,
2034 // together with those associated with X.
2036 // -- If T is a pointer to a data member of class X, its
2037 // associated namespaces and classes are those associated
2038 // with the member type together with those associated with
2040 case Type::MemberPointer: {
2041 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2043 // Queue up the class type into which this points.
2044 Queue.push_back(MemberPtr->getClass());
2046 // And directly continue with the pointee type.
2047 T = MemberPtr->getPointeeType().getTypePtr();
2051 // As an extension, treat this like a normal pointer.
2052 case Type::BlockPointer:
2053 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2056 // References aren't covered by the standard, but that's such an
2057 // obvious defect that we cover them anyway.
2058 case Type::LValueReference:
2059 case Type::RValueReference:
2060 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2063 // These are fundamental types.
2065 case Type::ExtVector:
2069 // If T is an Objective-C object or interface type, or a pointer to an
2070 // object or interface type, the associated namespace is the global
2072 case Type::ObjCObject:
2073 case Type::ObjCInterface:
2074 case Type::ObjCObjectPointer:
2075 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2078 // Atomic types are just wrappers; use the associations of the
2081 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2085 if (Queue.empty()) break;
2091 /// \brief Find the associated classes and namespaces for
2092 /// argument-dependent lookup for a call with the given set of
2095 /// This routine computes the sets of associated classes and associated
2096 /// namespaces searched by argument-dependent lookup
2097 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
2099 Sema::FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
2100 llvm::ArrayRef<Expr *> Args,
2101 AssociatedNamespaceSet &AssociatedNamespaces,
2102 AssociatedClassSet &AssociatedClasses) {
2103 AssociatedNamespaces.clear();
2104 AssociatedClasses.clear();
2106 AssociatedLookup Result(*this, InstantiationLoc,
2107 AssociatedNamespaces, AssociatedClasses);
2109 // C++ [basic.lookup.koenig]p2:
2110 // For each argument type T in the function call, there is a set
2111 // of zero or more associated namespaces and a set of zero or more
2112 // associated classes to be considered. The sets of namespaces and
2113 // classes is determined entirely by the types of the function
2114 // arguments (and the namespace of any template template
2116 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2117 Expr *Arg = Args[ArgIdx];
2119 if (Arg->getType() != Context.OverloadTy) {
2120 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2124 // [...] In addition, if the argument is the name or address of a
2125 // set of overloaded functions and/or function templates, its
2126 // associated classes and namespaces are the union of those
2127 // associated with each of the members of the set: the namespace
2128 // in which the function or function template is defined and the
2129 // classes and namespaces associated with its (non-dependent)
2130 // parameter types and return type.
2131 Arg = Arg->IgnoreParens();
2132 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2133 if (unaryOp->getOpcode() == UO_AddrOf)
2134 Arg = unaryOp->getSubExpr();
2136 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2139 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2141 // Look through any using declarations to find the underlying function.
2142 NamedDecl *Fn = (*I)->getUnderlyingDecl();
2144 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2146 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2148 // Add the classes and namespaces associated with the parameter
2149 // types and return type of this function.
2150 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2155 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2156 /// an acceptable non-member overloaded operator for a call whose
2157 /// arguments have types T1 (and, if non-empty, T2). This routine
2158 /// implements the check in C++ [over.match.oper]p3b2 concerning
2159 /// enumeration types.
2161 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2162 QualType T1, QualType T2,
2163 ASTContext &Context) {
2164 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2167 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2170 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2171 if (Proto->getNumArgs() < 1)
2174 if (T1->isEnumeralType()) {
2175 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2176 if (Context.hasSameUnqualifiedType(T1, ArgType))
2180 if (Proto->getNumArgs() < 2)
2183 if (!T2.isNull() && T2->isEnumeralType()) {
2184 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2185 if (Context.hasSameUnqualifiedType(T2, ArgType))
2192 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2194 LookupNameKind NameKind,
2195 RedeclarationKind Redecl) {
2196 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2198 return R.getAsSingle<NamedDecl>();
2201 /// \brief Find the protocol with the given name, if any.
2202 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2203 SourceLocation IdLoc,
2204 RedeclarationKind Redecl) {
2205 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2206 LookupObjCProtocolName, Redecl);
2207 return cast_or_null<ObjCProtocolDecl>(D);
2210 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2211 QualType T1, QualType T2,
2212 UnresolvedSetImpl &Functions) {
2213 // C++ [over.match.oper]p3:
2214 // -- The set of non-member candidates is the result of the
2215 // unqualified lookup of operator@ in the context of the
2216 // expression according to the usual rules for name lookup in
2217 // unqualified function calls (3.4.2) except that all member
2218 // functions are ignored. However, if no operand has a class
2219 // type, only those non-member functions in the lookup set
2220 // that have a first parameter of type T1 or "reference to
2221 // (possibly cv-qualified) T1", when T1 is an enumeration
2222 // type, or (if there is a right operand) a second parameter
2223 // of type T2 or "reference to (possibly cv-qualified) T2",
2224 // when T2 is an enumeration type, are candidate functions.
2225 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2226 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2227 LookupName(Operators, S);
2229 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2231 if (Operators.empty())
2234 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2235 Op != OpEnd; ++Op) {
2236 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2237 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2238 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2239 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2240 } else if (FunctionTemplateDecl *FunTmpl
2241 = dyn_cast<FunctionTemplateDecl>(Found)) {
2242 // FIXME: friend operators?
2243 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2245 if (!FunTmpl->getDeclContext()->isRecord())
2246 Functions.addDecl(*Op, Op.getAccess());
2251 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
2252 CXXSpecialMember SM,
2257 bool VolatileThis) {
2258 assert(CanDeclareSpecialMemberFunction(RD) &&
2259 "doing special member lookup into record that isn't fully complete");
2260 RD = RD->getDefinition();
2261 if (RValueThis || ConstThis || VolatileThis)
2262 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2263 "constructors and destructors always have unqualified lvalue this");
2264 if (ConstArg || VolatileArg)
2265 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2266 "parameter-less special members can't have qualified arguments");
2268 llvm::FoldingSetNodeID ID;
2271 ID.AddInteger(ConstArg);
2272 ID.AddInteger(VolatileArg);
2273 ID.AddInteger(RValueThis);
2274 ID.AddInteger(ConstThis);
2275 ID.AddInteger(VolatileThis);
2278 SpecialMemberOverloadResult *Result =
2279 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2281 // This was already cached
2285 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2286 Result = new (Result) SpecialMemberOverloadResult(ID);
2287 SpecialMemberCache.InsertNode(Result, InsertPoint);
2289 if (SM == CXXDestructor) {
2290 if (RD->needsImplicitDestructor())
2291 DeclareImplicitDestructor(RD);
2292 CXXDestructorDecl *DD = RD->getDestructor();
2293 assert(DD && "record without a destructor");
2294 Result->setMethod(DD);
2295 Result->setKind(DD->isDeleted() ?
2296 SpecialMemberOverloadResult::NoMemberOrDeleted :
2297 SpecialMemberOverloadResult::Success);
2301 // Prepare for overload resolution. Here we construct a synthetic argument
2302 // if necessary and make sure that implicit functions are declared.
2303 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2304 DeclarationName Name;
2308 QualType ArgType = CanTy;
2309 ExprValueKind VK = VK_LValue;
2311 if (SM == CXXDefaultConstructor) {
2312 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2314 if (RD->needsImplicitDefaultConstructor())
2315 DeclareImplicitDefaultConstructor(RD);
2317 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2318 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2319 if (RD->needsImplicitCopyConstructor())
2320 DeclareImplicitCopyConstructor(RD);
2321 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
2322 DeclareImplicitMoveConstructor(RD);
2324 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2325 if (RD->needsImplicitCopyAssignment())
2326 DeclareImplicitCopyAssignment(RD);
2327 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
2328 DeclareImplicitMoveAssignment(RD);
2334 ArgType.addVolatile();
2336 // This isn't /really/ specified by the standard, but it's implied
2337 // we should be working from an RValue in the case of move to ensure
2338 // that we prefer to bind to rvalue references, and an LValue in the
2339 // case of copy to ensure we don't bind to rvalue references.
2340 // Possibly an XValue is actually correct in the case of move, but
2341 // there is no semantic difference for class types in this restricted
2343 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2349 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2351 if (SM != CXXDefaultConstructor) {
2356 // Create the object argument
2357 QualType ThisTy = CanTy;
2361 ThisTy.addVolatile();
2362 Expr::Classification Classification =
2363 OpaqueValueExpr(SourceLocation(), ThisTy,
2364 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
2366 // Now we perform lookup on the name we computed earlier and do overload
2367 // resolution. Lookup is only performed directly into the class since there
2368 // will always be a (possibly implicit) declaration to shadow any others.
2369 OverloadCandidateSet OCS((SourceLocation()));
2370 DeclContext::lookup_result R = RD->lookup(Name);
2372 assert(!R.empty() &&
2373 "lookup for a constructor or assignment operator was empty");
2374 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
2377 if (Cand->isInvalidDecl())
2380 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2381 // FIXME: [namespace.udecl]p15 says that we should only consider a
2382 // using declaration here if it does not match a declaration in the
2383 // derived class. We do not implement this correctly in other cases
2385 Cand = U->getTargetDecl();
2387 if (Cand->isInvalidDecl())
2391 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
2392 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2393 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
2394 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2397 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2398 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2399 } else if (FunctionTemplateDecl *Tmpl =
2400 dyn_cast<FunctionTemplateDecl>(Cand)) {
2401 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2402 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2403 RD, 0, ThisTy, Classification,
2404 llvm::makeArrayRef(&Arg, NumArgs),
2407 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2408 0, llvm::makeArrayRef(&Arg, NumArgs),
2411 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
2415 OverloadCandidateSet::iterator Best;
2416 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2418 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2419 Result->setKind(SpecialMemberOverloadResult::Success);
2423 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2424 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2428 Result->setMethod(0);
2429 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2432 case OR_No_Viable_Function:
2433 Result->setMethod(0);
2434 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2441 /// \brief Look up the default constructor for the given class.
2442 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
2443 SpecialMemberOverloadResult *Result =
2444 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2447 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2450 /// \brief Look up the copying constructor for the given class.
2451 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2453 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2454 "non-const, non-volatile qualifiers for copy ctor arg");
2455 SpecialMemberOverloadResult *Result =
2456 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2457 Quals & Qualifiers::Volatile, false, false, false);
2459 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2462 /// \brief Look up the moving constructor for the given class.
2463 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2465 SpecialMemberOverloadResult *Result =
2466 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2467 Quals & Qualifiers::Volatile, false, false, false);
2469 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2472 /// \brief Look up the constructors for the given class.
2473 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2474 // If the implicit constructors have not yet been declared, do so now.
2475 if (CanDeclareSpecialMemberFunction(Class)) {
2476 if (Class->needsImplicitDefaultConstructor())
2477 DeclareImplicitDefaultConstructor(Class);
2478 if (Class->needsImplicitCopyConstructor())
2479 DeclareImplicitCopyConstructor(Class);
2480 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
2481 DeclareImplicitMoveConstructor(Class);
2484 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2485 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2486 return Class->lookup(Name);
2489 /// \brief Look up the copying assignment operator for the given class.
2490 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2491 unsigned Quals, bool RValueThis,
2492 unsigned ThisQuals) {
2493 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2494 "non-const, non-volatile qualifiers for copy assignment arg");
2495 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2496 "non-const, non-volatile qualifiers for copy assignment this");
2497 SpecialMemberOverloadResult *Result =
2498 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2499 Quals & Qualifiers::Volatile, RValueThis,
2500 ThisQuals & Qualifiers::Const,
2501 ThisQuals & Qualifiers::Volatile);
2503 return Result->getMethod();
2506 /// \brief Look up the moving assignment operator for the given class.
2507 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2510 unsigned ThisQuals) {
2511 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2512 "non-const, non-volatile qualifiers for copy assignment this");
2513 SpecialMemberOverloadResult *Result =
2514 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2515 Quals & Qualifiers::Volatile, RValueThis,
2516 ThisQuals & Qualifiers::Const,
2517 ThisQuals & Qualifiers::Volatile);
2519 return Result->getMethod();
2522 /// \brief Look for the destructor of the given class.
2524 /// During semantic analysis, this routine should be used in lieu of
2525 /// CXXRecordDecl::getDestructor().
2527 /// \returns The destructor for this class.
2528 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2529 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2530 false, false, false,
2531 false, false)->getMethod());
2534 /// LookupLiteralOperator - Determine which literal operator should be used for
2535 /// a user-defined literal, per C++11 [lex.ext].
2537 /// Normal overload resolution is not used to select which literal operator to
2538 /// call for a user-defined literal. Look up the provided literal operator name,
2539 /// and filter the results to the appropriate set for the given argument types.
2540 Sema::LiteralOperatorLookupResult
2541 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2542 ArrayRef<QualType> ArgTys,
2543 bool AllowRawAndTemplate) {
2545 assert(R.getResultKind() != LookupResult::Ambiguous &&
2546 "literal operator lookup can't be ambiguous");
2548 // Filter the lookup results appropriately.
2549 LookupResult::Filter F = R.makeFilter();
2551 bool FoundTemplate = false;
2552 bool FoundRaw = false;
2553 bool FoundExactMatch = false;
2555 while (F.hasNext()) {
2557 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2558 D = USD->getTargetDecl();
2560 bool IsTemplate = isa<FunctionTemplateDecl>(D);
2562 bool IsExactMatch = false;
2564 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2565 if (FD->getNumParams() == 1 &&
2566 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2568 else if (FD->getNumParams() == ArgTys.size()) {
2569 IsExactMatch = true;
2570 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2571 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2572 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2573 IsExactMatch = false;
2581 FoundExactMatch = true;
2582 AllowRawAndTemplate = false;
2583 if (FoundRaw || FoundTemplate) {
2584 // Go through again and remove the raw and template decls we've
2587 FoundRaw = FoundTemplate = false;
2589 } else if (AllowRawAndTemplate && (IsTemplate || IsRaw)) {
2590 FoundTemplate |= IsTemplate;
2599 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2600 // parameter type, that is used in preference to a raw literal operator
2601 // or literal operator template.
2602 if (FoundExactMatch)
2605 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2606 // operator template, but not both.
2607 if (FoundRaw && FoundTemplate) {
2608 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2609 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2611 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2612 D = USD->getTargetDecl();
2613 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2614 D = FunTmpl->getTemplatedDecl();
2615 NoteOverloadCandidate(cast<FunctionDecl>(D));
2624 return LOLR_Template;
2626 // Didn't find anything we could use.
2627 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2628 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2629 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRawAndTemplate;
2633 void ADLResult::insert(NamedDecl *New) {
2634 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2636 // If we haven't yet seen a decl for this key, or the last decl
2637 // was exactly this one, we're done.
2638 if (Old == 0 || Old == New) {
2643 // Otherwise, decide which is a more recent redeclaration.
2644 FunctionDecl *OldFD, *NewFD;
2645 if (isa<FunctionTemplateDecl>(New)) {
2646 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2647 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2649 OldFD = cast<FunctionDecl>(Old);
2650 NewFD = cast<FunctionDecl>(New);
2653 FunctionDecl *Cursor = NewFD;
2655 Cursor = Cursor->getPreviousDecl();
2657 // If we got to the end without finding OldFD, OldFD is the newer
2658 // declaration; leave things as they are.
2659 if (!Cursor) return;
2661 // If we do find OldFD, then NewFD is newer.
2662 if (Cursor == OldFD) break;
2664 // Otherwise, keep looking.
2670 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2672 llvm::ArrayRef<Expr *> Args,
2673 ADLResult &Result) {
2674 // Find all of the associated namespaces and classes based on the
2675 // arguments we have.
2676 AssociatedNamespaceSet AssociatedNamespaces;
2677 AssociatedClassSet AssociatedClasses;
2678 FindAssociatedClassesAndNamespaces(Loc, Args,
2679 AssociatedNamespaces,
2684 T1 = Args[0]->getType();
2685 if (Args.size() >= 2)
2686 T2 = Args[1]->getType();
2689 // C++ [basic.lookup.argdep]p3:
2690 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2691 // and let Y be the lookup set produced by argument dependent
2692 // lookup (defined as follows). If X contains [...] then Y is
2693 // empty. Otherwise Y is the set of declarations found in the
2694 // namespaces associated with the argument types as described
2695 // below. The set of declarations found by the lookup of the name
2696 // is the union of X and Y.
2698 // Here, we compute Y and add its members to the overloaded
2700 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2701 NSEnd = AssociatedNamespaces.end();
2702 NS != NSEnd; ++NS) {
2703 // When considering an associated namespace, the lookup is the
2704 // same as the lookup performed when the associated namespace is
2705 // used as a qualifier (3.4.3.2) except that:
2707 // -- Any using-directives in the associated namespace are
2710 // -- Any namespace-scope friend functions declared in
2711 // associated classes are visible within their respective
2712 // namespaces even if they are not visible during an ordinary
2714 DeclContext::lookup_result R = (*NS)->lookup(Name);
2715 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2718 // If the only declaration here is an ordinary friend, consider
2719 // it only if it was declared in an associated classes.
2720 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
2721 DeclContext *LexDC = D->getLexicalDeclContext();
2722 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2726 if (isa<UsingShadowDecl>(D))
2727 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2729 if (isa<FunctionDecl>(D)) {
2731 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2734 } else if (!isa<FunctionTemplateDecl>(D))
2742 //----------------------------------------------------------------------------
2743 // Search for all visible declarations.
2744 //----------------------------------------------------------------------------
2745 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2749 class ShadowContextRAII;
2751 class VisibleDeclsRecord {
2753 /// \brief An entry in the shadow map, which is optimized to store a
2754 /// single declaration (the common case) but can also store a list
2755 /// of declarations.
2756 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
2759 /// \brief A mapping from declaration names to the declarations that have
2760 /// this name within a particular scope.
2761 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2763 /// \brief A list of shadow maps, which is used to model name hiding.
2764 std::list<ShadowMap> ShadowMaps;
2766 /// \brief The declaration contexts we have already visited.
2767 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2769 friend class ShadowContextRAII;
2772 /// \brief Determine whether we have already visited this context
2773 /// (and, if not, note that we are going to visit that context now).
2774 bool visitedContext(DeclContext *Ctx) {
2775 return !VisitedContexts.insert(Ctx);
2778 bool alreadyVisitedContext(DeclContext *Ctx) {
2779 return VisitedContexts.count(Ctx);
2782 /// \brief Determine whether the given declaration is hidden in the
2785 /// \returns the declaration that hides the given declaration, or
2786 /// NULL if no such declaration exists.
2787 NamedDecl *checkHidden(NamedDecl *ND);
2789 /// \brief Add a declaration to the current shadow map.
2790 void add(NamedDecl *ND) {
2791 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
2795 /// \brief RAII object that records when we've entered a shadow context.
2796 class ShadowContextRAII {
2797 VisibleDeclsRecord &Visible;
2799 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2802 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2803 Visible.ShadowMaps.push_back(ShadowMap());
2806 ~ShadowContextRAII() {
2807 Visible.ShadowMaps.pop_back();
2811 } // end anonymous namespace
2813 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2814 // Look through using declarations.
2815 ND = ND->getUnderlyingDecl();
2817 unsigned IDNS = ND->getIdentifierNamespace();
2818 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2819 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2820 SM != SMEnd; ++SM) {
2821 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2822 if (Pos == SM->end())
2825 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2826 IEnd = Pos->second.end();
2828 // A tag declaration does not hide a non-tag declaration.
2829 if ((*I)->hasTagIdentifierNamespace() &&
2830 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2831 Decl::IDNS_ObjCProtocol)))
2834 // Protocols are in distinct namespaces from everything else.
2835 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2836 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2837 (*I)->getIdentifierNamespace() != IDNS)
2840 // Functions and function templates in the same scope overload
2841 // rather than hide. FIXME: Look for hiding based on function
2843 if ((*I)->isFunctionOrFunctionTemplate() &&
2844 ND->isFunctionOrFunctionTemplate() &&
2845 SM == ShadowMaps.rbegin())
2848 // We've found a declaration that hides this one.
2856 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2857 bool QualifiedNameLookup,
2859 VisibleDeclConsumer &Consumer,
2860 VisibleDeclsRecord &Visited) {
2864 // Make sure we don't visit the same context twice.
2865 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2868 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2869 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2871 // Enumerate all of the results in this context.
2872 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
2873 LEnd = Ctx->lookups_end();
2875 DeclContext::lookup_result R = *L;
2876 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2878 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
2879 if ((ND = Result.getAcceptableDecl(ND))) {
2880 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
2887 // Traverse using directives for qualified name lookup.
2888 if (QualifiedNameLookup) {
2889 ShadowContextRAII Shadow(Visited);
2890 DeclContext::udir_iterator I, E;
2891 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2892 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
2893 QualifiedNameLookup, InBaseClass, Consumer, Visited);
2897 // Traverse the contexts of inherited C++ classes.
2898 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2899 if (!Record->hasDefinition())
2902 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2903 BEnd = Record->bases_end();
2905 QualType BaseType = B->getType();
2907 // Don't look into dependent bases, because name lookup can't look
2909 if (BaseType->isDependentType())
2912 const RecordType *Record = BaseType->getAs<RecordType>();
2916 // FIXME: It would be nice to be able to determine whether referencing
2917 // a particular member would be ambiguous. For example, given
2919 // struct A { int member; };
2920 // struct B { int member; };
2921 // struct C : A, B { };
2923 // void f(C *c) { c->### }
2925 // accessing 'member' would result in an ambiguity. However, we
2926 // could be smart enough to qualify the member with the base
2935 // Find results in this base class (and its bases).
2936 ShadowContextRAII Shadow(Visited);
2937 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2938 true, Consumer, Visited);
2942 // Traverse the contexts of Objective-C classes.
2943 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2944 // Traverse categories.
2945 for (ObjCInterfaceDecl::visible_categories_iterator
2946 Cat = IFace->visible_categories_begin(),
2947 CatEnd = IFace->visible_categories_end();
2948 Cat != CatEnd; ++Cat) {
2949 ShadowContextRAII Shadow(Visited);
2950 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
2954 // Traverse protocols.
2955 for (ObjCInterfaceDecl::all_protocol_iterator
2956 I = IFace->all_referenced_protocol_begin(),
2957 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
2958 ShadowContextRAII Shadow(Visited);
2959 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2963 // Traverse the superclass.
2964 if (IFace->getSuperClass()) {
2965 ShadowContextRAII Shadow(Visited);
2966 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
2967 true, Consumer, Visited);
2970 // If there is an implementation, traverse it. We do this to find
2971 // synthesized ivars.
2972 if (IFace->getImplementation()) {
2973 ShadowContextRAII Shadow(Visited);
2974 LookupVisibleDecls(IFace->getImplementation(), Result,
2975 QualifiedNameLookup, InBaseClass, Consumer, Visited);
2977 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2978 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2979 E = Protocol->protocol_end(); I != E; ++I) {
2980 ShadowContextRAII Shadow(Visited);
2981 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2984 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2985 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2986 E = Category->protocol_end(); I != E; ++I) {
2987 ShadowContextRAII Shadow(Visited);
2988 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2992 // If there is an implementation, traverse it.
2993 if (Category->getImplementation()) {
2994 ShadowContextRAII Shadow(Visited);
2995 LookupVisibleDecls(Category->getImplementation(), Result,
2996 QualifiedNameLookup, true, Consumer, Visited);
3001 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3002 UnqualUsingDirectiveSet &UDirs,
3003 VisibleDeclConsumer &Consumer,
3004 VisibleDeclsRecord &Visited) {
3008 if (!S->getEntity() ||
3010 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
3011 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
3012 // Walk through the declarations in this Scope.
3013 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3015 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
3016 if ((ND = Result.getAcceptableDecl(ND))) {
3017 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
3023 // FIXME: C++ [temp.local]p8
3024 DeclContext *Entity = 0;
3025 if (S->getEntity()) {
3026 // Look into this scope's declaration context, along with any of its
3027 // parent lookup contexts (e.g., enclosing classes), up to the point
3028 // where we hit the context stored in the next outer scope.
3029 Entity = (DeclContext *)S->getEntity();
3030 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3032 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3033 Ctx = Ctx->getLookupParent()) {
3034 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3035 if (Method->isInstanceMethod()) {
3036 // For instance methods, look for ivars in the method's interface.
3037 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3038 Result.getNameLoc(), Sema::LookupMemberName);
3039 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3040 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3041 /*InBaseClass=*/false, Consumer, Visited);
3045 // We've already performed all of the name lookup that we need
3046 // to for Objective-C methods; the next context will be the
3051 if (Ctx->isFunctionOrMethod())
3054 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3055 /*InBaseClass=*/false, Consumer, Visited);
3057 } else if (!S->getParent()) {
3058 // Look into the translation unit scope. We walk through the translation
3059 // unit's declaration context, because the Scope itself won't have all of
3060 // the declarations if we loaded a precompiled header.
3061 // FIXME: We would like the translation unit's Scope object to point to the
3062 // translation unit, so we don't need this special "if" branch. However,
3063 // doing so would force the normal C++ name-lookup code to look into the
3064 // translation unit decl when the IdentifierInfo chains would suffice.
3065 // Once we fix that problem (which is part of a more general "don't look
3066 // in DeclContexts unless we have to" optimization), we can eliminate this.
3067 Entity = Result.getSema().Context.getTranslationUnitDecl();
3068 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3069 /*InBaseClass=*/false, Consumer, Visited);
3073 // Lookup visible declarations in any namespaces found by using
3075 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3076 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3077 for (; UI != UEnd; ++UI)
3078 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
3079 Result, /*QualifiedNameLookup=*/false,
3080 /*InBaseClass=*/false, Consumer, Visited);
3083 // Lookup names in the parent scope.
3084 ShadowContextRAII Shadow(Visited);
3085 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3088 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3089 VisibleDeclConsumer &Consumer,
3090 bool IncludeGlobalScope) {
3091 // Determine the set of using directives available during
3092 // unqualified name lookup.
3094 UnqualUsingDirectiveSet UDirs;
3095 if (getLangOpts().CPlusPlus) {
3096 // Find the first namespace or translation-unit scope.
3097 while (S && !isNamespaceOrTranslationUnitScope(S))
3100 UDirs.visitScopeChain(Initial, S);
3104 // Look for visible declarations.
3105 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3106 VisibleDeclsRecord Visited;
3107 if (!IncludeGlobalScope)
3108 Visited.visitedContext(Context.getTranslationUnitDecl());
3109 ShadowContextRAII Shadow(Visited);
3110 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3113 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3114 VisibleDeclConsumer &Consumer,
3115 bool IncludeGlobalScope) {
3116 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3117 VisibleDeclsRecord Visited;
3118 if (!IncludeGlobalScope)
3119 Visited.visitedContext(Context.getTranslationUnitDecl());
3120 ShadowContextRAII Shadow(Visited);
3121 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3122 /*InBaseClass=*/false, Consumer, Visited);
3125 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3126 /// If GnuLabelLoc is a valid source location, then this is a definition
3127 /// of an __label__ label name, otherwise it is a normal label definition
3129 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3130 SourceLocation GnuLabelLoc) {
3131 // Do a lookup to see if we have a label with this name already.
3134 if (GnuLabelLoc.isValid()) {
3135 // Local label definitions always shadow existing labels.
3136 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3137 Scope *S = CurScope;
3138 PushOnScopeChains(Res, S, true);
3139 return cast<LabelDecl>(Res);
3142 // Not a GNU local label.
3143 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3144 // If we found a label, check to see if it is in the same context as us.
3145 // When in a Block, we don't want to reuse a label in an enclosing function.
3146 if (Res && Res->getDeclContext() != CurContext)
3149 // If not forward referenced or defined already, create the backing decl.
3150 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3151 Scope *S = CurScope->getFnParent();
3152 assert(S && "Not in a function?");
3153 PushOnScopeChains(Res, S, true);
3155 return cast<LabelDecl>(Res);
3158 //===----------------------------------------------------------------------===//
3160 //===----------------------------------------------------------------------===//
3164 typedef SmallVector<TypoCorrection, 1> TypoResultList;
3165 typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
3166 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
3168 static const unsigned MaxTypoDistanceResultSets = 5;
3170 class TypoCorrectionConsumer : public VisibleDeclConsumer {
3171 /// \brief The name written that is a typo in the source.
3174 /// \brief The results found that have the smallest edit distance
3175 /// found (so far) with the typo name.
3177 /// The pointer value being set to the current DeclContext indicates
3178 /// whether there is a keyword with this name.
3179 TypoEditDistanceMap CorrectionResults;
3184 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
3185 : Typo(Typo->getName()),
3186 SemaRef(SemaRef) { }
3188 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3190 void FoundName(StringRef Name);
3191 void addKeywordResult(StringRef Keyword);
3192 void addName(StringRef Name, NamedDecl *ND, unsigned Distance,
3193 NestedNameSpecifier *NNS=NULL, bool isKeyword=false);
3194 void addCorrection(TypoCorrection Correction);
3196 typedef TypoResultsMap::iterator result_iterator;
3197 typedef TypoEditDistanceMap::iterator distance_iterator;
3198 distance_iterator begin() { return CorrectionResults.begin(); }
3199 distance_iterator end() { return CorrectionResults.end(); }
3200 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3201 unsigned size() const { return CorrectionResults.size(); }
3202 bool empty() const { return CorrectionResults.empty(); }
3204 TypoResultList &operator[](StringRef Name) {
3205 return CorrectionResults.begin()->second[Name];
3208 unsigned getBestEditDistance(bool Normalized) {
3209 if (CorrectionResults.empty())
3210 return (std::numeric_limits<unsigned>::max)();
3212 unsigned BestED = CorrectionResults.begin()->first;
3213 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
3216 TypoResultsMap &getBestResults() {
3217 return CorrectionResults.begin()->second;
3224 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3225 DeclContext *Ctx, bool InBaseClass) {
3226 // Don't consider hidden names for typo correction.
3230 // Only consider entities with identifiers for names, ignoring
3231 // special names (constructors, overloaded operators, selectors,
3233 IdentifierInfo *Name = ND->getIdentifier();
3237 FoundName(Name->getName());
3240 void TypoCorrectionConsumer::FoundName(StringRef Name) {
3241 // Use a simple length-based heuristic to determine the minimum possible
3242 // edit distance. If the minimum isn't good enough, bail out early.
3243 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
3244 if (MinED && Typo.size() / MinED < 3)
3247 // Compute an upper bound on the allowable edit distance, so that the
3248 // edit-distance algorithm can short-circuit.
3249 unsigned UpperBound = (Typo.size() + 2) / 3;
3251 // Compute the edit distance between the typo and the name of this
3252 // entity, and add the identifier to the list of results.
3253 addName(Name, NULL, Typo.edit_distance(Name, true, UpperBound));
3256 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3257 // Compute the edit distance between the typo and this keyword,
3258 // and add the keyword to the list of results.
3259 addName(Keyword, NULL, Typo.edit_distance(Keyword), NULL, true);
3262 void TypoCorrectionConsumer::addName(StringRef Name,
3265 NestedNameSpecifier *NNS,
3267 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, Distance);
3268 if (isKeyword) TC.makeKeyword();
3272 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3273 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3274 TypoResultList &CList =
3275 CorrectionResults[Correction.getEditDistance(false)][Name];
3277 if (!CList.empty() && !CList.back().isResolved())
3279 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3280 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3281 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3282 RI != RIEnd; ++RI) {
3283 // If the Correction refers to a decl already in the result list,
3284 // replace the existing result if the string representation of Correction
3285 // comes before the current result alphabetically, then stop as there is
3286 // nothing more to be done to add Correction to the candidate set.
3287 if (RI->getCorrectionDecl() == NewND) {
3288 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3294 if (CList.empty() || Correction.isResolved())
3295 CList.push_back(Correction);
3297 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3298 erase(llvm::prior(CorrectionResults.end()));
3301 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
3302 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3303 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3304 static void getNestedNameSpecifierIdentifiers(
3305 NestedNameSpecifier *NNS,
3306 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3307 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3308 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3310 Identifiers.clear();
3312 const IdentifierInfo *II = NULL;
3314 switch (NNS->getKind()) {
3315 case NestedNameSpecifier::Identifier:
3316 II = NNS->getAsIdentifier();
3319 case NestedNameSpecifier::Namespace:
3320 if (NNS->getAsNamespace()->isAnonymousNamespace())
3322 II = NNS->getAsNamespace()->getIdentifier();
3325 case NestedNameSpecifier::NamespaceAlias:
3326 II = NNS->getAsNamespaceAlias()->getIdentifier();
3329 case NestedNameSpecifier::TypeSpecWithTemplate:
3330 case NestedNameSpecifier::TypeSpec:
3331 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3334 case NestedNameSpecifier::Global:
3339 Identifiers.push_back(II);
3344 class SpecifierInfo {
3346 DeclContext* DeclCtx;
3347 NestedNameSpecifier* NameSpecifier;
3348 unsigned EditDistance;
3350 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3351 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3354 typedef SmallVector<DeclContext*, 4> DeclContextList;
3355 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3357 class NamespaceSpecifierSet {
3358 ASTContext &Context;
3359 DeclContextList CurContextChain;
3360 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3361 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
3364 SpecifierInfoList Specifiers;
3365 llvm::SmallSetVector<unsigned, 4> Distances;
3366 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3368 /// \brief Helper for building the list of DeclContexts between the current
3369 /// context and the top of the translation unit
3370 static DeclContextList BuildContextChain(DeclContext *Start);
3372 void SortNamespaces();
3375 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3376 CXXScopeSpec *CurScopeSpec)
3377 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3379 if (CurScopeSpec && CurScopeSpec->getScopeRep())
3380 getNestedNameSpecifierIdentifiers(CurScopeSpec->getScopeRep(),
3381 CurNameSpecifierIdentifiers);
3382 // Build the list of identifiers that would be used for an absolute
3383 // (from the global context) NestedNameSpecifier referring to the current
3385 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3386 CEnd = CurContextChain.rend();
3388 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3389 CurContextIdentifiers.push_back(ND->getIdentifier());
3393 /// \brief Add the namespace to the set, computing the corresponding
3394 /// NestedNameSpecifier and its distance in the process.
3395 void AddNamespace(NamespaceDecl *ND);
3397 typedef SpecifierInfoList::iterator iterator;
3399 if (!isSorted) SortNamespaces();
3400 return Specifiers.begin();
3402 iterator end() { return Specifiers.end(); }
3407 DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
3408 assert(Start && "Bulding a context chain from a null context");
3409 DeclContextList Chain;
3410 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3411 DC = DC->getLookupParent()) {
3412 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3413 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3414 !(ND && ND->isAnonymousNamespace()))
3415 Chain.push_back(DC->getPrimaryContext());
3420 void NamespaceSpecifierSet::SortNamespaces() {
3421 SmallVector<unsigned, 4> sortedDistances;
3422 sortedDistances.append(Distances.begin(), Distances.end());
3424 if (sortedDistances.size() > 1)
3425 std::sort(sortedDistances.begin(), sortedDistances.end());
3428 for (SmallVector<unsigned, 4>::iterator DI = sortedDistances.begin(),
3429 DIEnd = sortedDistances.end();
3430 DI != DIEnd; ++DI) {
3431 SpecifierInfoList &SpecList = DistanceMap[*DI];
3432 Specifiers.append(SpecList.begin(), SpecList.end());
3438 void NamespaceSpecifierSet::AddNamespace(NamespaceDecl *ND) {
3439 DeclContext *Ctx = cast<DeclContext>(ND);
3440 NestedNameSpecifier *NNS = NULL;
3441 unsigned NumSpecifiers = 0;
3442 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3443 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3445 // Eliminate common elements from the two DeclContext chains.
3446 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3447 CEnd = CurContextChain.rend();
3448 C != CEnd && !NamespaceDeclChain.empty() &&
3449 NamespaceDeclChain.back() == *C; ++C) {
3450 NamespaceDeclChain.pop_back();
3453 // Add an explicit leading '::' specifier if needed.
3454 if (NamespaceDecl *ND =
3455 NamespaceDeclChain.empty() ? NULL :
3456 dyn_cast_or_null<NamespaceDecl>(NamespaceDeclChain.back())) {
3457 IdentifierInfo *Name = ND->getIdentifier();
3458 if (std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3459 Name) != CurContextIdentifiers.end() ||
3460 std::find(CurNameSpecifierIdentifiers.begin(),
3461 CurNameSpecifierIdentifiers.end(),
3462 Name) != CurNameSpecifierIdentifiers.end()) {
3463 NamespaceDeclChain = FullNamespaceDeclChain;
3464 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3468 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3469 for (DeclContextList::reverse_iterator C = NamespaceDeclChain.rbegin(),
3470 CEnd = NamespaceDeclChain.rend();
3472 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C);
3474 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3479 // If the built NestedNameSpecifier would be replacing an existing
3480 // NestedNameSpecifier, use the number of component identifiers that
3481 // would need to be changed as the edit distance instead of the number
3482 // of components in the built NestedNameSpecifier.
3483 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3484 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3485 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3486 NumSpecifiers = llvm::ComputeEditDistance(
3487 llvm::ArrayRef<const IdentifierInfo*>(CurNameSpecifierIdentifiers),
3488 llvm::ArrayRef<const IdentifierInfo*>(NewNameSpecifierIdentifiers));
3492 Distances.insert(NumSpecifiers);
3493 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3496 /// \brief Perform name lookup for a possible result for typo correction.
3497 static void LookupPotentialTypoResult(Sema &SemaRef,
3499 IdentifierInfo *Name,
3500 Scope *S, CXXScopeSpec *SS,
3501 DeclContext *MemberContext,
3502 bool EnteringContext,
3503 bool isObjCIvarLookup) {
3504 Res.suppressDiagnostics();
3506 Res.setLookupName(Name);
3507 if (MemberContext) {
3508 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3509 if (isObjCIvarLookup) {
3510 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3517 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3524 SemaRef.LookupQualifiedName(Res, MemberContext);
3528 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3531 // Fake ivar lookup; this should really be part of
3532 // LookupParsedName.
3533 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3534 if (Method->isInstanceMethod() && Method->getClassInterface() &&
3536 (Res.isSingleResult() &&
3537 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3538 if (ObjCIvarDecl *IV
3539 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3547 /// \brief Add keywords to the consumer as possible typo corrections.
3548 static void AddKeywordsToConsumer(Sema &SemaRef,
3549 TypoCorrectionConsumer &Consumer,
3550 Scope *S, CorrectionCandidateCallback &CCC,
3551 bool AfterNestedNameSpecifier) {
3552 if (AfterNestedNameSpecifier) {
3553 // For 'X::', we know exactly which keywords can appear next.
3554 Consumer.addKeywordResult("template");
3555 if (CCC.WantExpressionKeywords)
3556 Consumer.addKeywordResult("operator");
3560 if (CCC.WantObjCSuper)
3561 Consumer.addKeywordResult("super");
3563 if (CCC.WantTypeSpecifiers) {
3564 // Add type-specifier keywords to the set of results.
3565 const char *CTypeSpecs[] = {
3566 "char", "const", "double", "enum", "float", "int", "long", "short",
3567 "signed", "struct", "union", "unsigned", "void", "volatile",
3568 "_Complex", "_Imaginary",
3569 // storage-specifiers as well
3570 "extern", "inline", "static", "typedef"
3573 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3574 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3575 Consumer.addKeywordResult(CTypeSpecs[I]);
3577 if (SemaRef.getLangOpts().C99)
3578 Consumer.addKeywordResult("restrict");
3579 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
3580 Consumer.addKeywordResult("bool");
3581 else if (SemaRef.getLangOpts().C99)
3582 Consumer.addKeywordResult("_Bool");
3584 if (SemaRef.getLangOpts().CPlusPlus) {
3585 Consumer.addKeywordResult("class");
3586 Consumer.addKeywordResult("typename");
3587 Consumer.addKeywordResult("wchar_t");
3589 if (SemaRef.getLangOpts().CPlusPlus11) {
3590 Consumer.addKeywordResult("char16_t");
3591 Consumer.addKeywordResult("char32_t");
3592 Consumer.addKeywordResult("constexpr");
3593 Consumer.addKeywordResult("decltype");
3594 Consumer.addKeywordResult("thread_local");
3598 if (SemaRef.getLangOpts().GNUMode)
3599 Consumer.addKeywordResult("typeof");
3602 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
3603 Consumer.addKeywordResult("const_cast");
3604 Consumer.addKeywordResult("dynamic_cast");
3605 Consumer.addKeywordResult("reinterpret_cast");
3606 Consumer.addKeywordResult("static_cast");
3609 if (CCC.WantExpressionKeywords) {
3610 Consumer.addKeywordResult("sizeof");
3611 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
3612 Consumer.addKeywordResult("false");
3613 Consumer.addKeywordResult("true");
3616 if (SemaRef.getLangOpts().CPlusPlus) {
3617 const char *CXXExprs[] = {
3618 "delete", "new", "operator", "throw", "typeid"
3620 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3621 for (unsigned I = 0; I != NumCXXExprs; ++I)
3622 Consumer.addKeywordResult(CXXExprs[I]);
3624 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3625 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3626 Consumer.addKeywordResult("this");
3628 if (SemaRef.getLangOpts().CPlusPlus11) {
3629 Consumer.addKeywordResult("alignof");
3630 Consumer.addKeywordResult("nullptr");
3634 if (SemaRef.getLangOpts().C11) {
3635 // FIXME: We should not suggest _Alignof if the alignof macro
3637 Consumer.addKeywordResult("_Alignof");
3641 if (CCC.WantRemainingKeywords) {
3642 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3644 const char *CStmts[] = {
3645 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3646 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3647 for (unsigned I = 0; I != NumCStmts; ++I)
3648 Consumer.addKeywordResult(CStmts[I]);
3650 if (SemaRef.getLangOpts().CPlusPlus) {
3651 Consumer.addKeywordResult("catch");
3652 Consumer.addKeywordResult("try");
3655 if (S && S->getBreakParent())
3656 Consumer.addKeywordResult("break");
3658 if (S && S->getContinueParent())
3659 Consumer.addKeywordResult("continue");
3661 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3662 Consumer.addKeywordResult("case");
3663 Consumer.addKeywordResult("default");
3666 if (SemaRef.getLangOpts().CPlusPlus) {
3667 Consumer.addKeywordResult("namespace");
3668 Consumer.addKeywordResult("template");
3671 if (S && S->isClassScope()) {
3672 Consumer.addKeywordResult("explicit");
3673 Consumer.addKeywordResult("friend");
3674 Consumer.addKeywordResult("mutable");
3675 Consumer.addKeywordResult("private");
3676 Consumer.addKeywordResult("protected");
3677 Consumer.addKeywordResult("public");
3678 Consumer.addKeywordResult("virtual");
3682 if (SemaRef.getLangOpts().CPlusPlus) {
3683 Consumer.addKeywordResult("using");
3685 if (SemaRef.getLangOpts().CPlusPlus11)
3686 Consumer.addKeywordResult("static_assert");
3691 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3692 TypoCorrection &Candidate) {
3693 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3694 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3697 /// \brief Try to "correct" a typo in the source code by finding
3698 /// visible declarations whose names are similar to the name that was
3699 /// present in the source code.
3701 /// \param TypoName the \c DeclarationNameInfo structure that contains
3702 /// the name that was present in the source code along with its location.
3704 /// \param LookupKind the name-lookup criteria used to search for the name.
3706 /// \param S the scope in which name lookup occurs.
3708 /// \param SS the nested-name-specifier that precedes the name we're
3709 /// looking for, if present.
3711 /// \param CCC A CorrectionCandidateCallback object that provides further
3712 /// validation of typo correction candidates. It also provides flags for
3713 /// determining the set of keywords permitted.
3715 /// \param MemberContext if non-NULL, the context in which to look for
3716 /// a member access expression.
3718 /// \param EnteringContext whether we're entering the context described by
3719 /// the nested-name-specifier SS.
3721 /// \param OPT when non-NULL, the search for visible declarations will
3722 /// also walk the protocols in the qualified interfaces of \p OPT.
3724 /// \returns a \c TypoCorrection containing the corrected name if the typo
3725 /// along with information such as the \c NamedDecl where the corrected name
3726 /// was declared, and any additional \c NestedNameSpecifier needed to access
3727 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
3728 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
3729 Sema::LookupNameKind LookupKind,
3730 Scope *S, CXXScopeSpec *SS,
3731 CorrectionCandidateCallback &CCC,
3732 DeclContext *MemberContext,
3733 bool EnteringContext,
3734 const ObjCObjectPointerType *OPT) {
3735 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking)
3736 return TypoCorrection();
3738 // In Microsoft mode, don't perform typo correction in a template member
3739 // function dependent context because it interferes with the "lookup into
3740 // dependent bases of class templates" feature.
3741 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
3742 isa<CXXMethodDecl>(CurContext))
3743 return TypoCorrection();
3745 // We only attempt to correct typos for identifiers.
3746 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
3748 return TypoCorrection();
3750 // If the scope specifier itself was invalid, don't try to correct
3752 if (SS && SS->isInvalid())
3753 return TypoCorrection();
3755 // Never try to correct typos during template deduction or
3757 if (!ActiveTemplateInstantiations.empty())
3758 return TypoCorrection();
3760 // Don't try to correct 'super'.
3761 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
3762 return TypoCorrection();
3764 // This is for testing.
3765 if (Diags.getWarnOnSpellCheck()) {
3766 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
3767 "spell-checking initiated for %0");
3768 Diag(TypoName.getLoc(), DiagID) << TypoName.getName();
3771 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
3773 TypoCorrectionConsumer Consumer(*this, Typo);
3775 // If a callback object considers an empty typo correction candidate to be
3776 // viable, assume it does not do any actual validation of the candidates.
3777 TypoCorrection EmptyCorrection;
3778 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
3780 // Perform name lookup to find visible, similarly-named entities.
3781 bool IsUnqualifiedLookup = false;
3782 DeclContext *QualifiedDC = MemberContext;
3783 if (MemberContext) {
3784 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
3786 // Look in qualified interfaces.
3788 for (ObjCObjectPointerType::qual_iterator
3789 I = OPT->qual_begin(), E = OPT->qual_end();
3791 LookupVisibleDecls(*I, LookupKind, Consumer);
3793 } else if (SS && SS->isSet()) {
3794 QualifiedDC = computeDeclContext(*SS, EnteringContext);
3796 return TypoCorrection();
3798 // Provide a stop gap for files that are just seriously broken. Trying
3799 // to correct all typos can turn into a HUGE performance penalty, causing
3800 // some files to take minutes to get rejected by the parser.
3801 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3802 return TypoCorrection();
3805 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
3807 IsUnqualifiedLookup = true;
3808 UnqualifiedTyposCorrectedMap::iterator Cached
3809 = UnqualifiedTyposCorrected.find(Typo);
3810 if (Cached != UnqualifiedTyposCorrected.end()) {
3811 // Add the cached value, unless it's a keyword or fails validation. In the
3812 // keyword case, we'll end up adding the keyword below.
3813 if (Cached->second) {
3814 if (!Cached->second.isKeyword() &&
3815 isCandidateViable(CCC, Cached->second))
3816 Consumer.addCorrection(Cached->second);
3818 // Only honor no-correction cache hits when a callback that will validate
3819 // correction candidates is not being used.
3820 if (!ValidatingCallback)
3821 return TypoCorrection();
3824 if (Cached == UnqualifiedTyposCorrected.end()) {
3825 // Provide a stop gap for files that are just seriously broken. Trying
3826 // to correct all typos can turn into a HUGE performance penalty, causing
3827 // some files to take minutes to get rejected by the parser.
3828 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3829 return TypoCorrection();
3833 // Determine whether we are going to search in the various namespaces for
3835 bool SearchNamespaces
3836 = getLangOpts().CPlusPlus &&
3837 (IsUnqualifiedLookup || (QualifiedDC && QualifiedDC->isNamespace()));
3838 // In a few cases we *only* want to search for corrections bases on just
3839 // adding or changing the nested name specifier.
3840 bool AllowOnlyNNSChanges = Typo->getName().size() < 3;
3842 if (IsUnqualifiedLookup || SearchNamespaces) {
3843 // For unqualified lookup, look through all of the names that we have
3844 // seen in this translation unit.
3845 // FIXME: Re-add the ability to skip very unlikely potential corrections.
3846 for (IdentifierTable::iterator I = Context.Idents.begin(),
3847 IEnd = Context.Idents.end();
3849 Consumer.FoundName(I->getKey());
3851 // Walk through identifiers in external identifier sources.
3852 // FIXME: Re-add the ability to skip very unlikely potential corrections.
3853 if (IdentifierInfoLookup *External
3854 = Context.Idents.getExternalIdentifierLookup()) {
3855 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
3857 StringRef Name = Iter->Next();
3861 Consumer.FoundName(Name);
3866 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
3868 // If we haven't found anything, we're done.
3869 if (Consumer.empty()) {
3870 // If this was an unqualified lookup, note that no correction was found.
3871 if (IsUnqualifiedLookup)
3872 (void)UnqualifiedTyposCorrected[Typo];
3874 return TypoCorrection();
3877 // Make sure the best edit distance (prior to adding any namespace qualifiers)
3878 // is not more that about a third of the length of the typo's identifier.
3879 unsigned ED = Consumer.getBestEditDistance(true);
3880 if (ED > 0 && Typo->getName().size() / ED < 3) {
3881 // If this was an unqualified lookup, note that no correction was found.
3882 if (IsUnqualifiedLookup)
3883 (void)UnqualifiedTyposCorrected[Typo];
3885 return TypoCorrection();
3888 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
3889 // to search those namespaces.
3890 if (SearchNamespaces) {
3891 // Load any externally-known namespaces.
3892 if (ExternalSource && !LoadedExternalKnownNamespaces) {
3893 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
3894 LoadedExternalKnownNamespaces = true;
3895 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
3896 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
3897 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
3900 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
3901 KNI = KnownNamespaces.begin(),
3902 KNIEnd = KnownNamespaces.end();
3903 KNI != KNIEnd; ++KNI)
3904 Namespaces.AddNamespace(KNI->first);
3907 // Weed out any names that could not be found by name lookup or, if a
3908 // CorrectionCandidateCallback object was provided, failed validation.
3909 SmallVector<TypoCorrection, 16> QualifiedResults;
3910 LookupResult TmpRes(*this, TypoName, LookupKind);
3911 TmpRes.suppressDiagnostics();
3912 while (!Consumer.empty()) {
3913 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
3914 unsigned ED = DI->first;
3915 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
3916 IEnd = DI->second.end();
3917 I != IEnd; /* Increment in loop. */) {
3918 // If we only want nested name specifier corrections, ignore potential
3919 // corrections that have a different base identifier from the typo.
3920 if (AllowOnlyNNSChanges &&
3921 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
3922 TypoCorrectionConsumer::result_iterator Prev = I;
3924 DI->second.erase(Prev);
3928 // If the item already has been looked up or is a keyword, keep it.
3929 // If a validator callback object was given, drop the correction
3930 // unless it passes validation.
3931 bool Viable = false;
3932 for (TypoResultList::iterator RI = I->second.begin();
3933 RI != I->second.end(); /* Increment in loop. */) {
3934 TypoResultList::iterator Prev = RI;
3936 if (Prev->isResolved()) {
3937 if (!isCandidateViable(CCC, *Prev))
3938 RI = I->second.erase(Prev);
3943 if (Viable || I->second.empty()) {
3944 TypoCorrectionConsumer::result_iterator Prev = I;
3947 DI->second.erase(Prev);
3950 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
3952 // Perform name lookup on this name.
3953 TypoCorrection &Candidate = I->second.front();
3954 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
3955 LookupPotentialTypoResult(*this, TmpRes, Name, S, SS, MemberContext,
3956 EnteringContext, CCC.IsObjCIvarLookup);
3958 switch (TmpRes.getResultKind()) {
3959 case LookupResult::NotFound:
3960 case LookupResult::NotFoundInCurrentInstantiation:
3961 case LookupResult::FoundUnresolvedValue:
3962 QualifiedResults.push_back(Candidate);
3963 // We didn't find this name in our scope, or didn't like what we found;
3966 TypoCorrectionConsumer::result_iterator Next = I;
3968 DI->second.erase(I);
3973 case LookupResult::Ambiguous:
3974 // We don't deal with ambiguities.
3975 return TypoCorrection();
3977 case LookupResult::FoundOverloaded: {
3978 TypoCorrectionConsumer::result_iterator Prev = I;
3979 // Store all of the Decls for overloaded symbols
3980 for (LookupResult::iterator TRD = TmpRes.begin(),
3981 TRDEnd = TmpRes.end();
3982 TRD != TRDEnd; ++TRD)
3983 Candidate.addCorrectionDecl(*TRD);
3985 if (!isCandidateViable(CCC, Candidate))
3986 DI->second.erase(Prev);
3990 case LookupResult::Found: {
3991 TypoCorrectionConsumer::result_iterator Prev = I;
3992 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
3994 if (!isCandidateViable(CCC, Candidate))
3995 DI->second.erase(Prev);
4002 if (DI->second.empty())
4004 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !ED)
4005 // If there are results in the closest possible bucket, stop
4008 // Only perform the qualified lookups for C++
4009 if (SearchNamespaces) {
4010 TmpRes.suppressDiagnostics();
4011 for (SmallVector<TypoCorrection,
4012 16>::iterator QRI = QualifiedResults.begin(),
4013 QRIEnd = QualifiedResults.end();
4014 QRI != QRIEnd; ++QRI) {
4015 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4016 NIEnd = Namespaces.end();
4017 NI != NIEnd; ++NI) {
4018 DeclContext *Ctx = NI->DeclCtx;
4020 // FIXME: Stop searching once the namespaces are too far away to create
4021 // acceptable corrections for this identifier (since the namespaces
4022 // are sorted in ascending order by edit distance).
4025 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
4026 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4028 // Any corrections added below will be validated in subsequent
4029 // iterations of the main while() loop over the Consumer's contents.
4030 switch (TmpRes.getResultKind()) {
4031 case LookupResult::Found: {
4032 TypoCorrection TC(*QRI);
4033 TC.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4034 TC.setCorrectionSpecifier(NI->NameSpecifier);
4035 TC.setQualifierDistance(NI->EditDistance);
4036 Consumer.addCorrection(TC);
4039 case LookupResult::FoundOverloaded: {
4040 TypoCorrection TC(*QRI);
4041 TC.setCorrectionSpecifier(NI->NameSpecifier);
4042 TC.setQualifierDistance(NI->EditDistance);
4043 for (LookupResult::iterator TRD = TmpRes.begin(),
4044 TRDEnd = TmpRes.end();
4045 TRD != TRDEnd; ++TRD)
4046 TC.addCorrectionDecl(*TRD);
4047 Consumer.addCorrection(TC);
4050 case LookupResult::NotFound:
4051 case LookupResult::NotFoundInCurrentInstantiation:
4052 case LookupResult::Ambiguous:
4053 case LookupResult::FoundUnresolvedValue:
4060 QualifiedResults.clear();
4063 // No corrections remain...
4064 if (Consumer.empty()) return TypoCorrection();
4066 TypoResultsMap &BestResults = Consumer.getBestResults();
4067 ED = Consumer.getBestEditDistance(true);
4069 if (!AllowOnlyNNSChanges && ED > 0 && Typo->getName().size() / ED < 3) {
4070 // If this was an unqualified lookup and we believe the callback
4071 // object wouldn't have filtered out possible corrections, note
4072 // that no correction was found.
4073 if (IsUnqualifiedLookup && !ValidatingCallback)
4074 (void)UnqualifiedTyposCorrected[Typo];
4076 return TypoCorrection();
4079 // If only a single name remains, return that result.
4080 if (BestResults.size() == 1) {
4081 const TypoResultList &CorrectionList = BestResults.begin()->second;
4082 const TypoCorrection &Result = CorrectionList.front();
4083 if (CorrectionList.size() != 1) return TypoCorrection();
4085 // Don't correct to a keyword that's the same as the typo; the keyword
4086 // wasn't actually in scope.
4087 if (ED == 0 && Result.isKeyword()) return TypoCorrection();
4089 // Record the correction for unqualified lookup.
4090 if (IsUnqualifiedLookup)
4091 UnqualifiedTyposCorrected[Typo] = Result;
4093 TypoCorrection TC = Result;
4094 TC.setCorrectionRange(SS, TypoName);
4097 else if (BestResults.size() > 1
4098 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4099 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4100 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4101 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4102 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
4103 && BestResults["super"].front().isKeyword()) {
4104 // Prefer 'super' when we're completing in a message-receiver
4107 // Don't correct to a keyword that's the same as the typo; the keyword
4108 // wasn't actually in scope.
4109 if (ED == 0) return TypoCorrection();
4111 // Record the correction for unqualified lookup.
4112 if (IsUnqualifiedLookup)
4113 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
4115 TypoCorrection TC = BestResults["super"].front();
4116 TC.setCorrectionRange(SS, TypoName);
4120 // If this was an unqualified lookup and we believe the callback object did
4121 // not filter out possible corrections, note that no correction was found.
4122 if (IsUnqualifiedLookup && !ValidatingCallback)
4123 (void)UnqualifiedTyposCorrected[Typo];
4125 return TypoCorrection();
4128 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4132 CorrectionDecls.clear();
4134 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
4136 if (!CorrectionName)
4137 CorrectionName = CDecl->getDeclName();
4140 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4141 if (CorrectionNameSpec) {
4142 std::string tmpBuffer;
4143 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4144 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4145 CorrectionName.printName(PrefixOStream);
4146 return PrefixOStream.str();
4149 return CorrectionName.getAsString();
4152 bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4153 if (!candidate.isResolved())
4156 if (candidate.isKeyword())
4157 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4158 WantRemainingKeywords || WantObjCSuper;
4160 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4161 CDeclEnd = candidate.end();
4162 CDecl != CDeclEnd; ++CDecl) {
4163 if (!isa<TypeDecl>(*CDecl))
4167 return WantTypeSpecifiers;