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 = InnermostFileScope->getEntity();
106 assert(InnermostFileDC && InnermostFileDC->isFileContext());
108 for (; S; S = S->getParent()) {
109 // C++ [namespace.udir]p1:
110 // A using-directive shall not appear in class scope, but may
111 // appear in namespace scope or in block scope.
112 DeclContext *Ctx = S->getEntity();
113 if (Ctx && Ctx->isFileContext()) {
115 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
116 Scope::udir_iterator I = S->using_directives_begin(),
117 End = S->using_directives_end();
118 for (; I != End; ++I)
119 visit(*I, InnermostFileDC);
124 // Visits a context and collect all of its using directives
125 // recursively. Treats all using directives as if they were
126 // declared in the context.
128 // A given context is only every visited once, so it is important
129 // that contexts be visited from the inside out in order to get
130 // the effective DCs right.
131 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
132 if (!visited.insert(DC))
135 addUsingDirectives(DC, EffectiveDC);
138 // Visits a using directive and collects all of its using
139 // directives recursively. Treats all using directives as if they
140 // were declared in the effective DC.
141 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (!visited.insert(NS))
146 addUsingDirective(UD, EffectiveDC);
147 addUsingDirectives(NS, EffectiveDC);
150 // Adds all the using directives in a context (and those nominated
151 // by its using directives, transitively) as if they appeared in
152 // the given effective context.
153 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
154 SmallVector<DeclContext*,4> queue;
156 DeclContext::udir_iterator I, End;
157 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) {
158 UsingDirectiveDecl *UD = *I;
159 DeclContext *NS = UD->getNominatedNamespace();
160 if (visited.insert(NS)) {
161 addUsingDirective(UD, EffectiveDC);
169 DC = queue.pop_back_val();
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
186 Common = Common->getPrimaryContext();
188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
192 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
195 typedef ListTy::const_iterator const_iterator;
197 const_iterator begin() const { return list.begin(); }
198 const_iterator end() const { return list.end(); }
200 std::pair<const_iterator,const_iterator>
201 getNamespacesFor(DeclContext *DC) const {
202 return std::equal_range(begin(), end(), DC->getPrimaryContext(),
203 UnqualUsingEntry::Comparator());
208 // Retrieve the set of identifier namespaces that correspond to a
209 // specific kind of name lookup.
210 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
212 bool Redeclaration) {
215 case Sema::LookupObjCImplicitSelfParam:
216 case Sema::LookupOrdinaryName:
217 case Sema::LookupRedeclarationWithLinkage:
218 case Sema::LookupLocalFriendName:
219 IDNS = Decl::IDNS_Ordinary;
221 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
223 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
226 IDNS |= Decl::IDNS_LocalExtern;
229 case Sema::LookupOperatorName:
230 // Operator lookup is its own crazy thing; it is not the same
231 // as (e.g.) looking up an operator name for redeclaration.
232 assert(!Redeclaration && "cannot do redeclaration operator lookup");
233 IDNS = Decl::IDNS_NonMemberOperator;
236 case Sema::LookupTagName:
238 IDNS = Decl::IDNS_Type;
240 // When looking for a redeclaration of a tag name, we add:
241 // 1) TagFriend to find undeclared friend decls
242 // 2) Namespace because they can't "overload" with tag decls.
243 // 3) Tag because it includes class templates, which can't
244 // "overload" with tag decls.
246 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
248 IDNS = Decl::IDNS_Tag;
251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
261 case Sema::LookupNestedNameSpecifierName:
262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
265 case Sema::LookupNamespaceName:
266 IDNS = Decl::IDNS_Namespace;
269 case Sema::LookupUsingDeclName:
270 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
271 | Decl::IDNS_Member | Decl::IDNS_Using;
274 case Sema::LookupObjCProtocolName:
275 IDNS = Decl::IDNS_ObjCProtocol;
278 case Sema::LookupAnyName:
279 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
280 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
287 void LookupResult::configure() {
288 IDNS = getIDNS(LookupKind, SemaRef.getLangOpts().CPlusPlus,
289 isForRedeclaration());
291 if (!isForRedeclaration()) {
292 // If we're looking for one of the allocation or deallocation
293 // operators, make sure that the implicitly-declared new and delete
294 // operators can be found.
295 switch (NameInfo.getName().getCXXOverloadedOperator()) {
299 case OO_Array_Delete:
300 SemaRef.DeclareGlobalNewDelete();
307 // Compiler builtins are always visible, regardless of where they end
308 // up being declared.
309 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
310 if (unsigned BuiltinID = Id->getBuiltinID()) {
311 if (!SemaRef.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
318 void LookupResult::sanityImpl() const {
319 // Note that this function is never called by NDEBUG builds. See
320 // LookupResult::sanity().
321 assert(ResultKind != NotFound || Decls.size() == 0);
322 assert(ResultKind != Found || Decls.size() == 1);
323 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
324 (Decls.size() == 1 &&
325 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
326 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
327 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
328 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
329 Ambiguity == AmbiguousBaseSubobjectTypes)));
330 assert((Paths != NULL) == (ResultKind == Ambiguous &&
331 (Ambiguity == AmbiguousBaseSubobjectTypes ||
332 Ambiguity == AmbiguousBaseSubobjects)));
335 // Necessary because CXXBasePaths is not complete in Sema.h
336 void LookupResult::deletePaths(CXXBasePaths *Paths) {
340 /// Get a representative context for a declaration such that two declarations
341 /// will have the same context if they were found within the same scope.
342 static DeclContext *getContextForScopeMatching(Decl *D) {
343 // For function-local declarations, use that function as the context. This
344 // doesn't account for scopes within the function; the caller must deal with
346 DeclContext *DC = D->getLexicalDeclContext();
347 if (DC->isFunctionOrMethod())
350 // Otherwise, look at the semantic context of the declaration. The
351 // declaration must have been found there.
352 return D->getDeclContext()->getRedeclContext();
355 /// Resolves the result kind of this lookup.
356 void LookupResult::resolveKind() {
357 unsigned N = Decls.size();
359 // Fast case: no possible ambiguity.
361 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
365 // If there's a single decl, we need to examine it to decide what
366 // kind of lookup this is.
368 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
369 if (isa<FunctionTemplateDecl>(D))
370 ResultKind = FoundOverloaded;
371 else if (isa<UnresolvedUsingValueDecl>(D))
372 ResultKind = FoundUnresolvedValue;
376 // Don't do any extra resolution if we've already resolved as ambiguous.
377 if (ResultKind == Ambiguous) return;
379 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
380 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
382 bool Ambiguous = false;
383 bool HasTag = false, HasFunction = false, HasNonFunction = false;
384 bool HasFunctionTemplate = false, HasUnresolved = false;
386 unsigned UniqueTagIndex = 0;
390 NamedDecl *D = Decls[I]->getUnderlyingDecl();
391 D = cast<NamedDecl>(D->getCanonicalDecl());
393 // Ignore an invalid declaration unless it's the only one left.
394 if (D->isInvalidDecl() && I < N-1) {
395 Decls[I] = Decls[--N];
399 // Redeclarations of types via typedef can occur both within a scope
400 // and, through using declarations and directives, across scopes. There is
401 // no ambiguity if they all refer to the same type, so unique based on the
403 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
404 if (!TD->getDeclContext()->isRecord()) {
405 QualType T = SemaRef.Context.getTypeDeclType(TD);
406 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
407 // The type is not unique; pull something off the back and continue
409 Decls[I] = Decls[--N];
415 if (!Unique.insert(D)) {
416 // If it's not unique, pull something off the back (and
417 // continue at this index).
418 Decls[I] = Decls[--N];
422 // Otherwise, do some decl type analysis and then continue.
424 if (isa<UnresolvedUsingValueDecl>(D)) {
425 HasUnresolved = true;
426 } else if (isa<TagDecl>(D)) {
431 } else if (isa<FunctionTemplateDecl>(D)) {
433 HasFunctionTemplate = true;
434 } else if (isa<FunctionDecl>(D)) {
439 HasNonFunction = true;
444 // C++ [basic.scope.hiding]p2:
445 // A class name or enumeration name can be hidden by the name of
446 // an object, function, or enumerator declared in the same
447 // scope. If a class or enumeration name and an object, function,
448 // or enumerator are declared in the same scope (in any order)
449 // with the same name, the class or enumeration name is hidden
450 // wherever the object, function, or enumerator name is visible.
451 // But it's still an error if there are distinct tag types found,
452 // even if they're not visible. (ref?)
453 if (HideTags && HasTag && !Ambiguous &&
454 (HasFunction || HasNonFunction || HasUnresolved)) {
455 if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
456 getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
457 Decls[UniqueTagIndex] = Decls[--N];
464 if (HasNonFunction && (HasFunction || HasUnresolved))
468 setAmbiguous(LookupResult::AmbiguousReference);
469 else if (HasUnresolved)
470 ResultKind = LookupResult::FoundUnresolvedValue;
471 else if (N > 1 || HasFunctionTemplate)
472 ResultKind = LookupResult::FoundOverloaded;
474 ResultKind = LookupResult::Found;
477 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
478 CXXBasePaths::const_paths_iterator I, E;
479 for (I = P.begin(), E = P.end(); I != E; ++I)
480 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
481 DE = I->Decls.end(); DI != DE; ++DI)
485 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
486 Paths = new CXXBasePaths;
488 addDeclsFromBasePaths(*Paths);
490 setAmbiguous(AmbiguousBaseSubobjects);
493 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
494 Paths = new CXXBasePaths;
496 addDeclsFromBasePaths(*Paths);
498 setAmbiguous(AmbiguousBaseSubobjectTypes);
501 void LookupResult::print(raw_ostream &Out) {
502 Out << Decls.size() << " result(s)";
503 if (isAmbiguous()) Out << ", ambiguous";
504 if (Paths) Out << ", base paths present";
506 for (iterator I = begin(), E = end(); I != E; ++I) {
512 /// \brief Lookup a builtin function, when name lookup would otherwise
514 static bool LookupBuiltin(Sema &S, LookupResult &R) {
515 Sema::LookupNameKind NameKind = R.getLookupKind();
517 // If we didn't find a use of this identifier, and if the identifier
518 // corresponds to a compiler builtin, create the decl object for the builtin
519 // now, injecting it into translation unit scope, and return it.
520 if (NameKind == Sema::LookupOrdinaryName ||
521 NameKind == Sema::LookupRedeclarationWithLinkage) {
522 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
524 if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
525 II == S.getFloat128Identifier()) {
526 // libstdc++4.7's type_traits expects type __float128 to exist, so
527 // insert a dummy type to make that header build in gnu++11 mode.
528 R.addDecl(S.getASTContext().getFloat128StubType());
532 // If this is a builtin on this (or all) targets, create the decl.
533 if (unsigned BuiltinID = II->getBuiltinID()) {
534 // In C++, we don't have any predefined library functions like
535 // 'malloc'. Instead, we'll just error.
536 if (S.getLangOpts().CPlusPlus &&
537 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
540 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
541 BuiltinID, S.TUScope,
542 R.isForRedeclaration(),
548 if (R.isForRedeclaration()) {
549 // If we're redeclaring this function anyway, forget that
550 // this was a builtin at all.
551 S.Context.BuiltinInfo.ForgetBuiltin(BuiltinID, S.Context.Idents);
562 /// \brief Determine whether we can declare a special member function within
563 /// the class at this point.
564 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
565 // We need to have a definition for the class.
566 if (!Class->getDefinition() || Class->isDependentContext())
569 // We can't be in the middle of defining the class.
570 return !Class->isBeingDefined();
573 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
574 if (!CanDeclareSpecialMemberFunction(Class))
577 // If the default constructor has not yet been declared, do so now.
578 if (Class->needsImplicitDefaultConstructor())
579 DeclareImplicitDefaultConstructor(Class);
581 // If the copy constructor has not yet been declared, do so now.
582 if (Class->needsImplicitCopyConstructor())
583 DeclareImplicitCopyConstructor(Class);
585 // If the copy assignment operator has not yet been declared, do so now.
586 if (Class->needsImplicitCopyAssignment())
587 DeclareImplicitCopyAssignment(Class);
589 if (getLangOpts().CPlusPlus11) {
590 // If the move constructor has not yet been declared, do so now.
591 if (Class->needsImplicitMoveConstructor())
592 DeclareImplicitMoveConstructor(Class); // might not actually do it
594 // If the move assignment operator has not yet been declared, do so now.
595 if (Class->needsImplicitMoveAssignment())
596 DeclareImplicitMoveAssignment(Class); // might not actually do it
599 // If the destructor has not yet been declared, do so now.
600 if (Class->needsImplicitDestructor())
601 DeclareImplicitDestructor(Class);
604 /// \brief Determine whether this is the name of an implicitly-declared
605 /// special member function.
606 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
607 switch (Name.getNameKind()) {
608 case DeclarationName::CXXConstructorName:
609 case DeclarationName::CXXDestructorName:
612 case DeclarationName::CXXOperatorName:
613 return Name.getCXXOverloadedOperator() == OO_Equal;
622 /// \brief If there are any implicit member functions with the given name
623 /// that need to be declared in the given declaration context, do so.
624 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
625 DeclarationName Name,
626 const DeclContext *DC) {
630 switch (Name.getNameKind()) {
631 case DeclarationName::CXXConstructorName:
632 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
633 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
634 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
635 if (Record->needsImplicitDefaultConstructor())
636 S.DeclareImplicitDefaultConstructor(Class);
637 if (Record->needsImplicitCopyConstructor())
638 S.DeclareImplicitCopyConstructor(Class);
639 if (S.getLangOpts().CPlusPlus11 &&
640 Record->needsImplicitMoveConstructor())
641 S.DeclareImplicitMoveConstructor(Class);
645 case DeclarationName::CXXDestructorName:
646 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
647 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
648 CanDeclareSpecialMemberFunction(Record))
649 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
652 case DeclarationName::CXXOperatorName:
653 if (Name.getCXXOverloadedOperator() != OO_Equal)
656 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
657 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
658 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
659 if (Record->needsImplicitCopyAssignment())
660 S.DeclareImplicitCopyAssignment(Class);
661 if (S.getLangOpts().CPlusPlus11 &&
662 Record->needsImplicitMoveAssignment())
663 S.DeclareImplicitMoveAssignment(Class);
673 // Adds all qualifying matches for a name within a decl context to the
674 // given lookup result. Returns true if any matches were found.
675 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
678 // Lazily declare C++ special member functions.
679 if (S.getLangOpts().CPlusPlus)
680 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
682 // Perform lookup into this declaration context.
683 DeclContext::lookup_const_result DR = DC->lookup(R.getLookupName());
684 for (DeclContext::lookup_const_iterator I = DR.begin(), E = DR.end(); I != E;
687 if ((D = R.getAcceptableDecl(D))) {
693 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
696 if (R.getLookupName().getNameKind()
697 != DeclarationName::CXXConversionFunctionName ||
698 R.getLookupName().getCXXNameType()->isDependentType() ||
699 !isa<CXXRecordDecl>(DC))
703 // A specialization of a conversion function template is not found by
704 // name lookup. Instead, any conversion function templates visible in the
705 // context of the use are considered. [...]
706 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
707 if (!Record->isCompleteDefinition())
710 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
711 UEnd = Record->conversion_end(); U != UEnd; ++U) {
712 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
716 // When we're performing lookup for the purposes of redeclaration, just
717 // add the conversion function template. When we deduce template
718 // arguments for specializations, we'll end up unifying the return
719 // type of the new declaration with the type of the function template.
720 if (R.isForRedeclaration()) {
721 R.addDecl(ConvTemplate);
727 // [...] For each such operator, if argument deduction succeeds
728 // (14.9.2.3), the resulting specialization is used as if found by
731 // When referencing a conversion function for any purpose other than
732 // a redeclaration (such that we'll be building an expression with the
733 // result), perform template argument deduction and place the
734 // specialization into the result set. We do this to avoid forcing all
735 // callers to perform special deduction for conversion functions.
736 TemplateDeductionInfo Info(R.getNameLoc());
737 FunctionDecl *Specialization = 0;
739 const FunctionProtoType *ConvProto
740 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
741 assert(ConvProto && "Nonsensical conversion function template type");
743 // Compute the type of the function that we would expect the conversion
744 // function to have, if it were to match the name given.
745 // FIXME: Calling convention!
746 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
747 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
748 EPI.ExceptionSpecType = EST_None;
749 EPI.NumExceptions = 0;
750 QualType ExpectedType
751 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
754 // Perform template argument deduction against the type that we would
755 // expect the function to have.
756 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
757 Specialization, Info)
758 == Sema::TDK_Success) {
759 R.addDecl(Specialization);
767 // Performs C++ unqualified lookup into the given file context.
769 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
770 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
772 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
774 // Perform direct name lookup into the LookupCtx.
775 bool Found = LookupDirect(S, R, NS);
777 // Perform direct name lookup into the namespaces nominated by the
778 // using directives whose common ancestor is this namespace.
779 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
780 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
782 for (; UI != UEnd; ++UI)
783 if (LookupDirect(S, R, UI->getNominatedNamespace()))
791 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
792 if (DeclContext *Ctx = S->getEntity())
793 return Ctx->isFileContext();
797 // Find the next outer declaration context from this scope. This
798 // routine actually returns the semantic outer context, which may
799 // differ from the lexical context (encoded directly in the Scope
800 // stack) when we are parsing a member of a class template. In this
801 // case, the second element of the pair will be true, to indicate that
802 // name lookup should continue searching in this semantic context when
803 // it leaves the current template parameter scope.
804 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
805 DeclContext *DC = S->getEntity();
806 DeclContext *Lexical = 0;
807 for (Scope *OuterS = S->getParent(); OuterS;
808 OuterS = OuterS->getParent()) {
809 if (OuterS->getEntity()) {
810 Lexical = OuterS->getEntity();
815 // C++ [temp.local]p8:
816 // In the definition of a member of a class template that appears
817 // outside of the namespace containing the class template
818 // definition, the name of a template-parameter hides the name of
819 // a member of this namespace.
826 // template<class T> class B {
831 // template<class C> void N::B<C>::f(C) {
832 // C b; // C is the template parameter, not N::C
835 // In this example, the lexical context we return is the
836 // TranslationUnit, while the semantic context is the namespace N.
837 if (!Lexical || !DC || !S->getParent() ||
838 !S->getParent()->isTemplateParamScope())
839 return std::make_pair(Lexical, false);
841 // Find the outermost template parameter scope.
842 // For the example, this is the scope for the template parameters of
843 // template<class C>.
844 Scope *OutermostTemplateScope = S->getParent();
845 while (OutermostTemplateScope->getParent() &&
846 OutermostTemplateScope->getParent()->isTemplateParamScope())
847 OutermostTemplateScope = OutermostTemplateScope->getParent();
849 // Find the namespace context in which the original scope occurs. In
850 // the example, this is namespace N.
851 DeclContext *Semantic = DC;
852 while (!Semantic->isFileContext())
853 Semantic = Semantic->getParent();
855 // Find the declaration context just outside of the template
856 // parameter scope. This is the context in which the template is
857 // being lexically declaration (a namespace context). In the
858 // example, this is the global scope.
859 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
860 Lexical->Encloses(Semantic))
861 return std::make_pair(Semantic, true);
863 return std::make_pair(Lexical, false);
867 /// An RAII object to specify that we want to find block scope extern
869 struct FindLocalExternScope {
870 FindLocalExternScope(LookupResult &R)
871 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
872 Decl::IDNS_LocalExtern) {
873 R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
876 R.setFindLocalExtern(OldFindLocalExtern);
878 ~FindLocalExternScope() {
882 bool OldFindLocalExtern;
886 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
887 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
889 DeclarationName Name = R.getLookupName();
890 Sema::LookupNameKind NameKind = R.getLookupKind();
892 // If this is the name of an implicitly-declared special member function,
893 // go through the scope stack to implicitly declare
894 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
895 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
896 if (DeclContext *DC = PreS->getEntity())
897 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
900 // Implicitly declare member functions with the name we're looking for, if in
901 // fact we are in a scope where it matters.
904 IdentifierResolver::iterator
905 I = IdResolver.begin(Name),
906 IEnd = IdResolver.end();
908 // First we lookup local scope.
909 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
910 // ...During unqualified name lookup (3.4.1), the names appear as if
911 // they were declared in the nearest enclosing namespace which contains
912 // both the using-directive and the nominated namespace.
913 // [Note: in this context, "contains" means "contains directly or
917 // namespace A { int i; }
921 // using namespace A;
922 // ++i; // finds local 'i', A::i appears at global scope
926 UnqualUsingDirectiveSet UDirs;
927 bool VisitedUsingDirectives = false;
928 bool LeftStartingScope = false;
929 DeclContext *OutsideOfTemplateParamDC = 0;
931 // When performing a scope lookup, we want to find local extern decls.
932 FindLocalExternScope FindLocals(R);
934 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
935 DeclContext *Ctx = S->getEntity();
937 // Check whether the IdResolver has anything in this scope.
939 for (; I != IEnd && S->isDeclScope(*I); ++I) {
940 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
941 if (NameKind == LookupRedeclarationWithLinkage) {
942 // Determine whether this (or a previous) declaration is
944 if (!LeftStartingScope && !Initial->isDeclScope(*I))
945 LeftStartingScope = true;
947 // If we found something outside of our starting scope that
948 // does not have linkage, skip it. If it's a template parameter,
949 // we still find it, so we can diagnose the invalid redeclaration.
950 if (LeftStartingScope && !((*I)->hasLinkage()) &&
951 !(*I)->isTemplateParameter()) {
963 if (S->isClassScope())
964 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
965 R.setNamingClass(Record);
969 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
970 // C++11 [class.friend]p11:
971 // If a friend declaration appears in a local class and the name
972 // specified is an unqualified name, a prior declaration is
973 // looked up without considering scopes that are outside the
974 // innermost enclosing non-class scope.
978 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
979 S->getParent() && !S->getParent()->isTemplateParamScope()) {
980 // We've just searched the last template parameter scope and
981 // found nothing, so look into the contexts between the
982 // lexical and semantic declaration contexts returned by
983 // findOuterContext(). This implements the name lookup behavior
984 // of C++ [temp.local]p8.
985 Ctx = OutsideOfTemplateParamDC;
986 OutsideOfTemplateParamDC = 0;
990 DeclContext *OuterCtx;
991 bool SearchAfterTemplateScope;
992 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
993 if (SearchAfterTemplateScope)
994 OutsideOfTemplateParamDC = OuterCtx;
996 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
997 // We do not directly look into transparent contexts, since
998 // those entities will be found in the nearest enclosing
999 // non-transparent context.
1000 if (Ctx->isTransparentContext())
1003 // We do not look directly into function or method contexts,
1004 // since all of the local variables and parameters of the
1005 // function/method are present within the Scope.
1006 if (Ctx->isFunctionOrMethod()) {
1007 // If we have an Objective-C instance method, look for ivars
1008 // in the corresponding interface.
1009 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1010 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1011 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1012 ObjCInterfaceDecl *ClassDeclared;
1013 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1014 Name.getAsIdentifierInfo(),
1016 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1028 // If this is a file context, we need to perform unqualified name
1029 // lookup considering using directives.
1030 if (Ctx->isFileContext()) {
1031 // If we haven't handled using directives yet, do so now.
1032 if (!VisitedUsingDirectives) {
1033 // Add using directives from this context up to the top level.
1034 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1035 if (UCtx->isTransparentContext())
1038 UDirs.visit(UCtx, UCtx);
1041 // Find the innermost file scope, so we can add using directives
1042 // from local scopes.
1043 Scope *InnermostFileScope = S;
1044 while (InnermostFileScope &&
1045 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1046 InnermostFileScope = InnermostFileScope->getParent();
1047 UDirs.visitScopeChain(Initial, InnermostFileScope);
1051 VisitedUsingDirectives = true;
1054 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1062 // Perform qualified name lookup into this context.
1063 // FIXME: In some cases, we know that every name that could be found by
1064 // this qualified name lookup will also be on the identifier chain. For
1065 // example, inside a class without any base classes, we never need to
1066 // perform qualified lookup because all of the members are on top of the
1067 // identifier chain.
1068 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1074 // Stop if we ran out of scopes.
1075 // FIXME: This really, really shouldn't be happening.
1076 if (!S) return false;
1078 // If we are looking for members, no need to look into global/namespace scope.
1079 if (NameKind == LookupMemberName)
1082 // Collect UsingDirectiveDecls in all scopes, and recursively all
1083 // nominated namespaces by those using-directives.
1085 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1086 // don't build it for each lookup!
1087 if (!VisitedUsingDirectives) {
1088 UDirs.visitScopeChain(Initial, S);
1092 // If we're not performing redeclaration lookup, do not look for local
1093 // extern declarations outside of a function scope.
1094 if (!R.isForRedeclaration())
1095 FindLocals.restore();
1097 // Lookup namespace scope, and global scope.
1098 // Unqualified name lookup in C++ requires looking into scopes
1099 // that aren't strictly lexical, and therefore we walk through the
1100 // context as well as walking through the scopes.
1101 for (; S; S = S->getParent()) {
1102 // Check whether the IdResolver has anything in this scope.
1104 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1105 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1106 // We found something. Look for anything else in our scope
1107 // with this same name and in an acceptable identifier
1108 // namespace, so that we can construct an overload set if we
1115 if (Found && S->isTemplateParamScope()) {
1120 DeclContext *Ctx = S->getEntity();
1121 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1122 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1123 // We've just searched the last template parameter scope and
1124 // found nothing, so look into the contexts between the
1125 // lexical and semantic declaration contexts returned by
1126 // findOuterContext(). This implements the name lookup behavior
1127 // of C++ [temp.local]p8.
1128 Ctx = OutsideOfTemplateParamDC;
1129 OutsideOfTemplateParamDC = 0;
1133 DeclContext *OuterCtx;
1134 bool SearchAfterTemplateScope;
1135 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1136 if (SearchAfterTemplateScope)
1137 OutsideOfTemplateParamDC = OuterCtx;
1139 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1140 // We do not directly look into transparent contexts, since
1141 // those entities will be found in the nearest enclosing
1142 // non-transparent context.
1143 if (Ctx->isTransparentContext())
1146 // If we have a context, and it's not a context stashed in the
1147 // template parameter scope for an out-of-line definition, also
1148 // look into that context.
1149 if (!(Found && S && S->isTemplateParamScope())) {
1150 assert(Ctx->isFileContext() &&
1151 "We should have been looking only at file context here already.");
1153 // Look into context considering using-directives.
1154 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1163 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1168 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1175 /// \brief Find the declaration that a class temploid member specialization was
1176 /// instantiated from, or the member itself if it is an explicit specialization.
1177 static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
1178 return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
1181 /// \brief Find the module in which the given declaration was defined.
1182 static Module *getDefiningModule(Decl *Entity) {
1183 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1184 // If this function was instantiated from a template, the defining module is
1185 // the module containing the pattern.
1186 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1188 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1189 // If it's a class template specialization, find the template or partial
1190 // specialization from which it was instantiated.
1191 if (ClassTemplateSpecializationDecl *SpecRD =
1192 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1193 llvm::PointerUnion<ClassTemplateDecl*,
1194 ClassTemplatePartialSpecializationDecl*> From =
1195 SpecRD->getInstantiatedFrom();
1196 if (ClassTemplateDecl *FromTemplate = From.dyn_cast<ClassTemplateDecl*>())
1197 Entity = FromTemplate->getTemplatedDecl();
1199 Entity = From.get<ClassTemplatePartialSpecializationDecl*>();
1200 // Otherwise, it's an explicit specialization.
1201 } else if (MemberSpecializationInfo *MSInfo =
1202 RD->getMemberSpecializationInfo())
1203 Entity = getInstantiatedFrom(RD, MSInfo);
1204 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1205 if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
1206 Entity = getInstantiatedFrom(ED, MSInfo);
1207 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1208 // FIXME: Map from variable template specializations back to the template.
1209 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
1210 Entity = getInstantiatedFrom(VD, MSInfo);
1213 // Walk up to the containing context. That might also have been instantiated
1215 DeclContext *Context = Entity->getDeclContext();
1216 if (Context->isFileContext())
1217 return Entity->getOwningModule();
1218 return getDefiningModule(cast<Decl>(Context));
1221 llvm::DenseSet<Module*> &Sema::getLookupModules() {
1222 unsigned N = ActiveTemplateInstantiations.size();
1223 for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
1225 Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
1226 if (M && !LookupModulesCache.insert(M).second)
1228 ActiveTemplateInstantiationLookupModules.push_back(M);
1230 return LookupModulesCache;
1233 /// \brief Determine whether a declaration is visible to name lookup.
1235 /// This routine determines whether the declaration D is visible in the current
1236 /// lookup context, taking into account the current template instantiation
1237 /// stack. During template instantiation, a declaration is visible if it is
1238 /// visible from a module containing any entity on the template instantiation
1239 /// path (by instantiating a template, you allow it to see the declarations that
1240 /// your module can see, including those later on in your module).
1241 bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1242 assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
1243 "should not call this: not in slow case");
1244 Module *DeclModule = D->getOwningModule();
1245 assert(DeclModule && "hidden decl not from a module");
1247 // Find the extra places where we need to look.
1248 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1249 if (LookupModules.empty())
1252 // If our lookup set contains the decl's module, it's visible.
1253 if (LookupModules.count(DeclModule))
1256 // If the declaration isn't exported, it's not visible in any other module.
1257 if (D->isModulePrivate())
1260 // Check whether DeclModule is transitively exported to an import of
1262 for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
1263 E = LookupModules.end();
1265 if ((*I)->isModuleVisible(DeclModule))
1270 /// \brief Retrieve the visible declaration corresponding to D, if any.
1272 /// This routine determines whether the declaration D is visible in the current
1273 /// module, with the current imports. If not, it checks whether any
1274 /// redeclaration of D is visible, and if so, returns that declaration.
1276 /// \returns D, or a visible previous declaration of D, whichever is more recent
1277 /// and visible. If no declaration of D is visible, returns null.
1278 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1279 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
1281 for (Decl::redecl_iterator RD = D->redecls_begin(), RDEnd = D->redecls_end();
1282 RD != RDEnd; ++RD) {
1283 if (NamedDecl *ND = dyn_cast<NamedDecl>(*RD)) {
1284 if (LookupResult::isVisible(SemaRef, ND))
1292 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1293 return findAcceptableDecl(SemaRef, D);
1296 /// @brief Perform unqualified name lookup starting from a given
1299 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1300 /// used to find names within the current scope. For example, 'x' in
1304 /// return x; // unqualified name look finds 'x' in the global scope
1308 /// Different lookup criteria can find different names. For example, a
1309 /// particular scope can have both a struct and a function of the same
1310 /// name, and each can be found by certain lookup criteria. For more
1311 /// information about lookup criteria, see the documentation for the
1312 /// class LookupCriteria.
1314 /// @param S The scope from which unqualified name lookup will
1315 /// begin. If the lookup criteria permits, name lookup may also search
1316 /// in the parent scopes.
1318 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1319 /// look up and the lookup kind), and is updated with the results of lookup
1320 /// including zero or more declarations and possibly additional information
1321 /// used to diagnose ambiguities.
1323 /// @returns \c true if lookup succeeded and false otherwise.
1324 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1325 DeclarationName Name = R.getLookupName();
1326 if (!Name) return false;
1328 LookupNameKind NameKind = R.getLookupKind();
1330 if (!getLangOpts().CPlusPlus) {
1331 // Unqualified name lookup in C/Objective-C is purely lexical, so
1332 // search in the declarations attached to the name.
1333 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1334 // Find the nearest non-transparent declaration scope.
1335 while (!(S->getFlags() & Scope::DeclScope) ||
1336 (S->getEntity() && S->getEntity()->isTransparentContext()))
1340 // When performing a scope lookup, we want to find local extern decls.
1341 FindLocalExternScope FindLocals(R);
1343 // Scan up the scope chain looking for a decl that matches this
1344 // identifier that is in the appropriate namespace. This search
1345 // should not take long, as shadowing of names is uncommon, and
1346 // deep shadowing is extremely uncommon.
1347 bool LeftStartingScope = false;
1349 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1350 IEnd = IdResolver.end();
1352 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
1353 if (NameKind == LookupRedeclarationWithLinkage) {
1354 // Determine whether this (or a previous) declaration is
1356 if (!LeftStartingScope && !S->isDeclScope(*I))
1357 LeftStartingScope = true;
1359 // If we found something outside of our starting scope that
1360 // does not have linkage, skip it.
1361 if (LeftStartingScope && !((*I)->hasLinkage())) {
1366 else if (NameKind == LookupObjCImplicitSelfParam &&
1367 !isa<ImplicitParamDecl>(*I))
1372 // Check whether there are any other declarations with the same name
1373 // and in the same scope.
1375 // Find the scope in which this declaration was declared (if it
1376 // actually exists in a Scope).
1377 while (S && !S->isDeclScope(D))
1380 // If the scope containing the declaration is the translation unit,
1381 // then we'll need to perform our checks based on the matching
1382 // DeclContexts rather than matching scopes.
1383 if (S && isNamespaceOrTranslationUnitScope(S))
1386 // Compute the DeclContext, if we need it.
1387 DeclContext *DC = 0;
1389 DC = (*I)->getDeclContext()->getRedeclContext();
1391 IdentifierResolver::iterator LastI = I;
1392 for (++LastI; LastI != IEnd; ++LastI) {
1394 // Match based on scope.
1395 if (!S->isDeclScope(*LastI))
1398 // Match based on DeclContext.
1400 = (*LastI)->getDeclContext()->getRedeclContext();
1401 if (!LastDC->Equals(DC))
1405 // If the declaration is in the right namespace and visible, add it.
1406 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1416 // Perform C++ unqualified name lookup.
1417 if (CppLookupName(R, S))
1421 // If we didn't find a use of this identifier, and if the identifier
1422 // corresponds to a compiler builtin, create the decl object for the builtin
1423 // now, injecting it into translation unit scope, and return it.
1424 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1427 // If we didn't find a use of this identifier, the ExternalSource
1428 // may be able to handle the situation.
1429 // Note: some lookup failures are expected!
1430 // See e.g. R.isForRedeclaration().
1431 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1434 /// @brief Perform qualified name lookup in the namespaces nominated by
1435 /// using directives by the given context.
1437 /// C++98 [namespace.qual]p2:
1438 /// Given X::m (where X is a user-declared namespace), or given \::m
1439 /// (where X is the global namespace), let S be the set of all
1440 /// declarations of m in X and in the transitive closure of all
1441 /// namespaces nominated by using-directives in X and its used
1442 /// namespaces, except that using-directives are ignored in any
1443 /// namespace, including X, directly containing one or more
1444 /// declarations of m. No namespace is searched more than once in
1445 /// the lookup of a name. If S is the empty set, the program is
1446 /// ill-formed. Otherwise, if S has exactly one member, or if the
1447 /// context of the reference is a using-declaration
1448 /// (namespace.udecl), S is the required set of declarations of
1449 /// m. Otherwise if the use of m is not one that allows a unique
1450 /// declaration to be chosen from S, the program is ill-formed.
1452 /// C++98 [namespace.qual]p5:
1453 /// During the lookup of a qualified namespace member name, if the
1454 /// lookup finds more than one declaration of the member, and if one
1455 /// declaration introduces a class name or enumeration name and the
1456 /// other declarations either introduce the same object, the same
1457 /// enumerator or a set of functions, the non-type name hides the
1458 /// class or enumeration name if and only if the declarations are
1459 /// from the same namespace; otherwise (the declarations are from
1460 /// different namespaces), the program is ill-formed.
1461 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1462 DeclContext *StartDC) {
1463 assert(StartDC->isFileContext() && "start context is not a file context");
1465 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1466 DeclContext::udir_iterator E = StartDC->using_directives_end();
1468 if (I == E) return false;
1470 // We have at least added all these contexts to the queue.
1471 llvm::SmallPtrSet<DeclContext*, 8> Visited;
1472 Visited.insert(StartDC);
1474 // We have not yet looked into these namespaces, much less added
1475 // their "using-children" to the queue.
1476 SmallVector<NamespaceDecl*, 8> Queue;
1478 // We have already looked into the initial namespace; seed the queue
1479 // with its using-children.
1480 for (; I != E; ++I) {
1481 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1482 if (Visited.insert(ND))
1483 Queue.push_back(ND);
1486 // The easiest way to implement the restriction in [namespace.qual]p5
1487 // is to check whether any of the individual results found a tag
1488 // and, if so, to declare an ambiguity if the final result is not
1490 bool FoundTag = false;
1491 bool FoundNonTag = false;
1493 LookupResult LocalR(LookupResult::Temporary, R);
1496 while (!Queue.empty()) {
1497 NamespaceDecl *ND = Queue.pop_back_val();
1499 // We go through some convolutions here to avoid copying results
1500 // between LookupResults.
1501 bool UseLocal = !R.empty();
1502 LookupResult &DirectR = UseLocal ? LocalR : R;
1503 bool FoundDirect = LookupDirect(S, DirectR, ND);
1506 // First do any local hiding.
1507 DirectR.resolveKind();
1509 // If the local result is a tag, remember that.
1510 if (DirectR.isSingleTagDecl())
1515 // Append the local results to the total results if necessary.
1517 R.addAllDecls(LocalR);
1522 // If we find names in this namespace, ignore its using directives.
1528 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1529 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1530 if (Visited.insert(Nom))
1531 Queue.push_back(Nom);
1536 if (FoundTag && FoundNonTag)
1537 R.setAmbiguousQualifiedTagHiding();
1545 /// \brief Callback that looks for any member of a class with the given name.
1546 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1549 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1551 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1552 Path.Decls = BaseRecord->lookup(N);
1553 return !Path.Decls.empty();
1556 /// \brief Determine whether the given set of member declarations contains only
1557 /// static members, nested types, and enumerators.
1558 template<typename InputIterator>
1559 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1560 Decl *D = (*First)->getUnderlyingDecl();
1561 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1564 if (isa<CXXMethodDecl>(D)) {
1565 // Determine whether all of the methods are static.
1566 bool AllMethodsAreStatic = true;
1567 for(; First != Last; ++First) {
1568 D = (*First)->getUnderlyingDecl();
1570 if (!isa<CXXMethodDecl>(D)) {
1571 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1575 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1576 AllMethodsAreStatic = false;
1581 if (AllMethodsAreStatic)
1588 /// \brief Perform qualified name lookup into a given context.
1590 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1591 /// names when the context of those names is explicit specified, e.g.,
1592 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1594 /// Different lookup criteria can find different names. For example, a
1595 /// particular scope can have both a struct and a function of the same
1596 /// name, and each can be found by certain lookup criteria. For more
1597 /// information about lookup criteria, see the documentation for the
1598 /// class LookupCriteria.
1600 /// \param R captures both the lookup criteria and any lookup results found.
1602 /// \param LookupCtx The context in which qualified name lookup will
1603 /// search. If the lookup criteria permits, name lookup may also search
1604 /// in the parent contexts or (for C++ classes) base classes.
1606 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1607 /// occurs as part of unqualified name lookup.
1609 /// \returns true if lookup succeeded, false if it failed.
1610 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1611 bool InUnqualifiedLookup) {
1612 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1614 if (!R.getLookupName())
1617 // Make sure that the declaration context is complete.
1618 assert((!isa<TagDecl>(LookupCtx) ||
1619 LookupCtx->isDependentContext() ||
1620 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
1621 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
1622 "Declaration context must already be complete!");
1624 // Perform qualified name lookup into the LookupCtx.
1625 if (LookupDirect(*this, R, LookupCtx)) {
1627 if (isa<CXXRecordDecl>(LookupCtx))
1628 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1632 // Don't descend into implied contexts for redeclarations.
1633 // C++98 [namespace.qual]p6:
1634 // In a declaration for a namespace member in which the
1635 // declarator-id is a qualified-id, given that the qualified-id
1636 // for the namespace member has the form
1637 // nested-name-specifier unqualified-id
1638 // the unqualified-id shall name a member of the namespace
1639 // designated by the nested-name-specifier.
1640 // See also [class.mfct]p5 and [class.static.data]p2.
1641 if (R.isForRedeclaration())
1644 // If this is a namespace, look it up in the implied namespaces.
1645 if (LookupCtx->isFileContext())
1646 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1648 // If this isn't a C++ class, we aren't allowed to look into base
1649 // classes, we're done.
1650 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1651 if (!LookupRec || !LookupRec->getDefinition())
1654 // If we're performing qualified name lookup into a dependent class,
1655 // then we are actually looking into a current instantiation. If we have any
1656 // dependent base classes, then we either have to delay lookup until
1657 // template instantiation time (at which point all bases will be available)
1658 // or we have to fail.
1659 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1660 LookupRec->hasAnyDependentBases()) {
1661 R.setNotFoundInCurrentInstantiation();
1665 // Perform lookup into our base classes.
1667 Paths.setOrigin(LookupRec);
1669 // Look for this member in our base classes
1670 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1671 switch (R.getLookupKind()) {
1672 case LookupObjCImplicitSelfParam:
1673 case LookupOrdinaryName:
1674 case LookupMemberName:
1675 case LookupRedeclarationWithLinkage:
1676 case LookupLocalFriendName:
1677 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1681 BaseCallback = &CXXRecordDecl::FindTagMember;
1685 BaseCallback = &LookupAnyMember;
1688 case LookupUsingDeclName:
1689 // This lookup is for redeclarations only.
1691 case LookupOperatorName:
1692 case LookupNamespaceName:
1693 case LookupObjCProtocolName:
1695 // These lookups will never find a member in a C++ class (or base class).
1698 case LookupNestedNameSpecifierName:
1699 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1703 if (!LookupRec->lookupInBases(BaseCallback,
1704 R.getLookupName().getAsOpaquePtr(), Paths))
1707 R.setNamingClass(LookupRec);
1709 // C++ [class.member.lookup]p2:
1710 // [...] If the resulting set of declarations are not all from
1711 // sub-objects of the same type, or the set has a nonstatic member
1712 // and includes members from distinct sub-objects, there is an
1713 // ambiguity and the program is ill-formed. Otherwise that set is
1714 // the result of the lookup.
1715 QualType SubobjectType;
1716 int SubobjectNumber = 0;
1717 AccessSpecifier SubobjectAccess = AS_none;
1719 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1720 Path != PathEnd; ++Path) {
1721 const CXXBasePathElement &PathElement = Path->back();
1723 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1724 // across all paths.
1725 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1727 // Determine whether we're looking at a distinct sub-object or not.
1728 if (SubobjectType.isNull()) {
1729 // This is the first subobject we've looked at. Record its type.
1730 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1731 SubobjectNumber = PathElement.SubobjectNumber;
1736 != Context.getCanonicalType(PathElement.Base->getType())) {
1737 // We found members of the given name in two subobjects of
1738 // different types. If the declaration sets aren't the same, this
1739 // this lookup is ambiguous.
1740 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
1741 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1742 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
1743 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
1745 while (FirstD != FirstPath->Decls.end() &&
1746 CurrentD != Path->Decls.end()) {
1747 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1748 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1755 if (FirstD == FirstPath->Decls.end() &&
1756 CurrentD == Path->Decls.end())
1760 R.setAmbiguousBaseSubobjectTypes(Paths);
1764 if (SubobjectNumber != PathElement.SubobjectNumber) {
1765 // We have a different subobject of the same type.
1767 // C++ [class.member.lookup]p5:
1768 // A static member, a nested type or an enumerator defined in
1769 // a base class T can unambiguously be found even if an object
1770 // has more than one base class subobject of type T.
1771 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
1774 // We have found a nonstatic member name in multiple, distinct
1775 // subobjects. Name lookup is ambiguous.
1776 R.setAmbiguousBaseSubobjects(Paths);
1781 // Lookup in a base class succeeded; return these results.
1783 DeclContext::lookup_result DR = Paths.front().Decls;
1784 for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E; ++I) {
1786 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1794 /// @brief Performs name lookup for a name that was parsed in the
1795 /// source code, and may contain a C++ scope specifier.
1797 /// This routine is a convenience routine meant to be called from
1798 /// contexts that receive a name and an optional C++ scope specifier
1799 /// (e.g., "N::M::x"). It will then perform either qualified or
1800 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1801 /// respectively) on the given name and return those results.
1803 /// @param S The scope from which unqualified name lookup will
1806 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1808 /// @param EnteringContext Indicates whether we are going to enter the
1809 /// context of the scope-specifier SS (if present).
1811 /// @returns True if any decls were found (but possibly ambiguous)
1812 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1813 bool AllowBuiltinCreation, bool EnteringContext) {
1814 if (SS && SS->isInvalid()) {
1815 // When the scope specifier is invalid, don't even look for
1820 if (SS && SS->isSet()) {
1821 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1822 // We have resolved the scope specifier to a particular declaration
1823 // contex, and will perform name lookup in that context.
1824 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1827 R.setContextRange(SS->getRange());
1828 return LookupQualifiedName(R, DC);
1831 // We could not resolve the scope specified to a specific declaration
1832 // context, which means that SS refers to an unknown specialization.
1833 // Name lookup can't find anything in this case.
1834 R.setNotFoundInCurrentInstantiation();
1835 R.setContextRange(SS->getRange());
1839 // Perform unqualified name lookup starting in the given scope.
1840 return LookupName(R, S, AllowBuiltinCreation);
1844 /// \brief Produce a diagnostic describing the ambiguity that resulted
1845 /// from name lookup.
1847 /// \param Result The result of the ambiguous lookup to be diagnosed.
1848 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1849 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1851 DeclarationName Name = Result.getLookupName();
1852 SourceLocation NameLoc = Result.getNameLoc();
1853 SourceRange LookupRange = Result.getContextRange();
1855 switch (Result.getAmbiguityKind()) {
1856 case LookupResult::AmbiguousBaseSubobjects: {
1857 CXXBasePaths *Paths = Result.getBasePaths();
1858 QualType SubobjectType = Paths->front().back().Base->getType();
1859 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1860 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1863 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
1864 while (isa<CXXMethodDecl>(*Found) &&
1865 cast<CXXMethodDecl>(*Found)->isStatic())
1868 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1872 case LookupResult::AmbiguousBaseSubobjectTypes: {
1873 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1874 << Name << LookupRange;
1876 CXXBasePaths *Paths = Result.getBasePaths();
1877 std::set<Decl *> DeclsPrinted;
1878 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1879 PathEnd = Paths->end();
1880 Path != PathEnd; ++Path) {
1881 Decl *D = Path->Decls.front();
1882 if (DeclsPrinted.insert(D).second)
1883 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1888 case LookupResult::AmbiguousTagHiding: {
1889 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1891 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1893 LookupResult::iterator DI, DE = Result.end();
1894 for (DI = Result.begin(); DI != DE; ++DI)
1895 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1896 TagDecls.insert(TD);
1897 Diag(TD->getLocation(), diag::note_hidden_tag);
1900 for (DI = Result.begin(); DI != DE; ++DI)
1901 if (!isa<TagDecl>(*DI))
1902 Diag((*DI)->getLocation(), diag::note_hiding_object);
1904 // For recovery purposes, go ahead and implement the hiding.
1905 LookupResult::Filter F = Result.makeFilter();
1906 while (F.hasNext()) {
1907 if (TagDecls.count(F.next()))
1914 case LookupResult::AmbiguousReference: {
1915 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1917 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1918 for (; DI != DE; ++DI)
1919 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1926 struct AssociatedLookup {
1927 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
1928 Sema::AssociatedNamespaceSet &Namespaces,
1929 Sema::AssociatedClassSet &Classes)
1930 : S(S), Namespaces(Namespaces), Classes(Classes),
1931 InstantiationLoc(InstantiationLoc) {
1935 Sema::AssociatedNamespaceSet &Namespaces;
1936 Sema::AssociatedClassSet &Classes;
1937 SourceLocation InstantiationLoc;
1942 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1944 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1946 // Add the associated namespace for this class.
1948 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1949 // be a locally scoped record.
1951 // We skip out of inline namespaces. The innermost non-inline namespace
1952 // contains all names of all its nested inline namespaces anyway, so we can
1953 // replace the entire inline namespace tree with its root.
1954 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1955 Ctx->isInlineNamespace())
1956 Ctx = Ctx->getParent();
1958 if (Ctx->isFileContext())
1959 Namespaces.insert(Ctx->getPrimaryContext());
1962 // \brief Add the associated classes and namespaces for argument-dependent
1963 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1965 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1966 const TemplateArgument &Arg) {
1967 // C++ [basic.lookup.koenig]p2, last bullet:
1969 switch (Arg.getKind()) {
1970 case TemplateArgument::Null:
1973 case TemplateArgument::Type:
1974 // [...] the namespaces and classes associated with the types of the
1975 // template arguments provided for template type parameters (excluding
1976 // template template parameters)
1977 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1980 case TemplateArgument::Template:
1981 case TemplateArgument::TemplateExpansion: {
1982 // [...] the namespaces in which any template template arguments are
1983 // defined; and the classes in which any member templates used as
1984 // template template arguments are defined.
1985 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
1986 if (ClassTemplateDecl *ClassTemplate
1987 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1988 DeclContext *Ctx = ClassTemplate->getDeclContext();
1989 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1990 Result.Classes.insert(EnclosingClass);
1991 // Add the associated namespace for this class.
1992 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1997 case TemplateArgument::Declaration:
1998 case TemplateArgument::Integral:
1999 case TemplateArgument::Expression:
2000 case TemplateArgument::NullPtr:
2001 // [Note: non-type template arguments do not contribute to the set of
2002 // associated namespaces. ]
2005 case TemplateArgument::Pack:
2006 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
2007 PEnd = Arg.pack_end();
2009 addAssociatedClassesAndNamespaces(Result, *P);
2014 // \brief Add the associated classes and namespaces for
2015 // argument-dependent lookup with an argument of class type
2016 // (C++ [basic.lookup.koenig]p2).
2018 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2019 CXXRecordDecl *Class) {
2021 // Just silently ignore anything whose name is __va_list_tag.
2022 if (Class->getDeclName() == Result.S.VAListTagName)
2025 // C++ [basic.lookup.koenig]p2:
2027 // -- If T is a class type (including unions), its associated
2028 // classes are: the class itself; the class of which it is a
2029 // member, if any; and its direct and indirect base
2030 // classes. Its associated namespaces are the namespaces in
2031 // which its associated classes are defined.
2033 // Add the class of which it is a member, if any.
2034 DeclContext *Ctx = Class->getDeclContext();
2035 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2036 Result.Classes.insert(EnclosingClass);
2037 // Add the associated namespace for this class.
2038 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2040 // Add the class itself. If we've already seen this class, we don't
2041 // need to visit base classes.
2042 if (!Result.Classes.insert(Class))
2045 // -- If T is a template-id, its associated namespaces and classes are
2046 // the namespace in which the template is defined; for member
2047 // templates, the member template's class; the namespaces and classes
2048 // associated with the types of the template arguments provided for
2049 // template type parameters (excluding template template parameters); the
2050 // namespaces in which any template template arguments are defined; and
2051 // the classes in which any member templates used as template template
2052 // arguments are defined. [Note: non-type template arguments do not
2053 // contribute to the set of associated namespaces. ]
2054 if (ClassTemplateSpecializationDecl *Spec
2055 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2056 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2057 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2058 Result.Classes.insert(EnclosingClass);
2059 // Add the associated namespace for this class.
2060 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2062 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2063 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2064 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2067 // Only recurse into base classes for complete types.
2068 if (!Class->hasDefinition()) {
2069 QualType type = Result.S.Context.getTypeDeclType(Class);
2070 if (Result.S.RequireCompleteType(Result.InstantiationLoc, type,
2071 /*no diagnostic*/ 0))
2075 // Add direct and indirect base classes along with their associated
2077 SmallVector<CXXRecordDecl *, 32> Bases;
2078 Bases.push_back(Class);
2079 while (!Bases.empty()) {
2080 // Pop this class off the stack.
2081 Class = Bases.pop_back_val();
2083 // Visit the base classes.
2084 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
2085 BaseEnd = Class->bases_end();
2086 Base != BaseEnd; ++Base) {
2087 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
2088 // In dependent contexts, we do ADL twice, and the first time around,
2089 // the base type might be a dependent TemplateSpecializationType, or a
2090 // TemplateTypeParmType. If that happens, simply ignore it.
2091 // FIXME: If we want to support export, we probably need to add the
2092 // namespace of the template in a TemplateSpecializationType, or even
2093 // the classes and namespaces of known non-dependent arguments.
2096 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2097 if (Result.Classes.insert(BaseDecl)) {
2098 // Find the associated namespace for this base class.
2099 DeclContext *BaseCtx = BaseDecl->getDeclContext();
2100 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2102 // Make sure we visit the bases of this base class.
2103 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2104 Bases.push_back(BaseDecl);
2110 // \brief Add the associated classes and namespaces for
2111 // argument-dependent lookup with an argument of type T
2112 // (C++ [basic.lookup.koenig]p2).
2114 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2115 // C++ [basic.lookup.koenig]p2:
2117 // For each argument type T in the function call, there is a set
2118 // of zero or more associated namespaces and a set of zero or more
2119 // associated classes to be considered. The sets of namespaces and
2120 // classes is determined entirely by the types of the function
2121 // arguments (and the namespace of any template template
2122 // argument). Typedef names and using-declarations used to specify
2123 // the types do not contribute to this set. The sets of namespaces
2124 // and classes are determined in the following way:
2126 SmallVector<const Type *, 16> Queue;
2127 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2130 switch (T->getTypeClass()) {
2132 #define TYPE(Class, Base)
2133 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2134 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2135 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2136 #define ABSTRACT_TYPE(Class, Base)
2137 #include "clang/AST/TypeNodes.def"
2138 // T is canonical. We can also ignore dependent types because
2139 // we don't need to do ADL at the definition point, but if we
2140 // wanted to implement template export (or if we find some other
2141 // use for associated classes and namespaces...) this would be
2145 // -- If T is a pointer to U or an array of U, its associated
2146 // namespaces and classes are those associated with U.
2148 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2150 case Type::ConstantArray:
2151 case Type::IncompleteArray:
2152 case Type::VariableArray:
2153 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2156 // -- If T is a fundamental type, its associated sets of
2157 // namespaces and classes are both empty.
2161 // -- If T is a class type (including unions), its associated
2162 // classes are: the class itself; the class of which it is a
2163 // member, if any; and its direct and indirect base
2164 // classes. Its associated namespaces are the namespaces in
2165 // which its associated classes are defined.
2166 case Type::Record: {
2167 CXXRecordDecl *Class
2168 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2169 addAssociatedClassesAndNamespaces(Result, Class);
2173 // -- If T is an enumeration type, its associated namespace is
2174 // the namespace in which it is defined. If it is class
2175 // member, its associated class is the member's class; else
2176 // it has no associated class.
2178 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2180 DeclContext *Ctx = Enum->getDeclContext();
2181 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2182 Result.Classes.insert(EnclosingClass);
2184 // Add the associated namespace for this class.
2185 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2190 // -- If T is a function type, its associated namespaces and
2191 // classes are those associated with the function parameter
2192 // types and those associated with the return type.
2193 case Type::FunctionProto: {
2194 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2195 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2196 ArgEnd = Proto->arg_type_end();
2197 Arg != ArgEnd; ++Arg)
2198 Queue.push_back(Arg->getTypePtr());
2201 case Type::FunctionNoProto: {
2202 const FunctionType *FnType = cast<FunctionType>(T);
2203 T = FnType->getResultType().getTypePtr();
2207 // -- If T is a pointer to a member function of a class X, its
2208 // associated namespaces and classes are those associated
2209 // with the function parameter types and return type,
2210 // together with those associated with X.
2212 // -- If T is a pointer to a data member of class X, its
2213 // associated namespaces and classes are those associated
2214 // with the member type together with those associated with
2216 case Type::MemberPointer: {
2217 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2219 // Queue up the class type into which this points.
2220 Queue.push_back(MemberPtr->getClass());
2222 // And directly continue with the pointee type.
2223 T = MemberPtr->getPointeeType().getTypePtr();
2227 // As an extension, treat this like a normal pointer.
2228 case Type::BlockPointer:
2229 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2232 // References aren't covered by the standard, but that's such an
2233 // obvious defect that we cover them anyway.
2234 case Type::LValueReference:
2235 case Type::RValueReference:
2236 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2239 // These are fundamental types.
2241 case Type::ExtVector:
2245 // Non-deduced auto types only get here for error cases.
2249 // If T is an Objective-C object or interface type, or a pointer to an
2250 // object or interface type, the associated namespace is the global
2252 case Type::ObjCObject:
2253 case Type::ObjCInterface:
2254 case Type::ObjCObjectPointer:
2255 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2258 // Atomic types are just wrappers; use the associations of the
2261 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2267 T = Queue.pop_back_val();
2271 /// \brief Find the associated classes and namespaces for
2272 /// argument-dependent lookup for a call with the given set of
2275 /// This routine computes the sets of associated classes and associated
2276 /// namespaces searched by argument-dependent lookup
2277 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
2278 void Sema::FindAssociatedClassesAndNamespaces(
2279 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2280 AssociatedNamespaceSet &AssociatedNamespaces,
2281 AssociatedClassSet &AssociatedClasses) {
2282 AssociatedNamespaces.clear();
2283 AssociatedClasses.clear();
2285 AssociatedLookup Result(*this, InstantiationLoc,
2286 AssociatedNamespaces, AssociatedClasses);
2288 // C++ [basic.lookup.koenig]p2:
2289 // For each argument type T in the function call, there is a set
2290 // of zero or more associated namespaces and a set of zero or more
2291 // associated classes to be considered. The sets of namespaces and
2292 // classes is determined entirely by the types of the function
2293 // arguments (and the namespace of any template template
2295 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2296 Expr *Arg = Args[ArgIdx];
2298 if (Arg->getType() != Context.OverloadTy) {
2299 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2303 // [...] In addition, if the argument is the name or address of a
2304 // set of overloaded functions and/or function templates, its
2305 // associated classes and namespaces are the union of those
2306 // associated with each of the members of the set: the namespace
2307 // in which the function or function template is defined and the
2308 // classes and namespaces associated with its (non-dependent)
2309 // parameter types and return type.
2310 Arg = Arg->IgnoreParens();
2311 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2312 if (unaryOp->getOpcode() == UO_AddrOf)
2313 Arg = unaryOp->getSubExpr();
2315 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2318 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2320 // Look through any using declarations to find the underlying function.
2321 NamedDecl *Fn = (*I)->getUnderlyingDecl();
2323 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2325 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2327 // Add the classes and namespaces associated with the parameter
2328 // types and return type of this function.
2329 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2334 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2335 /// an acceptable non-member overloaded operator for a call whose
2336 /// arguments have types T1 (and, if non-empty, T2). This routine
2337 /// implements the check in C++ [over.match.oper]p3b2 concerning
2338 /// enumeration types.
2340 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2341 QualType T1, QualType T2,
2342 ASTContext &Context) {
2343 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2346 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2349 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2350 if (Proto->getNumArgs() < 1)
2353 if (T1->isEnumeralType()) {
2354 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2355 if (Context.hasSameUnqualifiedType(T1, ArgType))
2359 if (Proto->getNumArgs() < 2)
2362 if (!T2.isNull() && T2->isEnumeralType()) {
2363 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2364 if (Context.hasSameUnqualifiedType(T2, ArgType))
2371 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2373 LookupNameKind NameKind,
2374 RedeclarationKind Redecl) {
2375 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2377 return R.getAsSingle<NamedDecl>();
2380 /// \brief Find the protocol with the given name, if any.
2381 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2382 SourceLocation IdLoc,
2383 RedeclarationKind Redecl) {
2384 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2385 LookupObjCProtocolName, Redecl);
2386 return cast_or_null<ObjCProtocolDecl>(D);
2389 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2390 QualType T1, QualType T2,
2391 UnresolvedSetImpl &Functions) {
2392 // C++ [over.match.oper]p3:
2393 // -- The set of non-member candidates is the result of the
2394 // unqualified lookup of operator@ in the context of the
2395 // expression according to the usual rules for name lookup in
2396 // unqualified function calls (3.4.2) except that all member
2397 // functions are ignored. However, if no operand has a class
2398 // type, only those non-member functions in the lookup set
2399 // that have a first parameter of type T1 or "reference to
2400 // (possibly cv-qualified) T1", when T1 is an enumeration
2401 // type, or (if there is a right operand) a second parameter
2402 // of type T2 or "reference to (possibly cv-qualified) T2",
2403 // when T2 is an enumeration type, are candidate functions.
2404 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2405 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2406 LookupName(Operators, S);
2408 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2410 if (Operators.empty())
2413 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2414 Op != OpEnd; ++Op) {
2415 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2416 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2417 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2418 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2419 } else if (FunctionTemplateDecl *FunTmpl
2420 = dyn_cast<FunctionTemplateDecl>(Found)) {
2421 // FIXME: friend operators?
2422 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2424 if (!FunTmpl->getDeclContext()->isRecord())
2425 Functions.addDecl(*Op, Op.getAccess());
2430 Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
2431 CXXSpecialMember SM,
2436 bool VolatileThis) {
2437 assert(CanDeclareSpecialMemberFunction(RD) &&
2438 "doing special member lookup into record that isn't fully complete");
2439 RD = RD->getDefinition();
2440 if (RValueThis || ConstThis || VolatileThis)
2441 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2442 "constructors and destructors always have unqualified lvalue this");
2443 if (ConstArg || VolatileArg)
2444 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2445 "parameter-less special members can't have qualified arguments");
2447 llvm::FoldingSetNodeID ID;
2450 ID.AddInteger(ConstArg);
2451 ID.AddInteger(VolatileArg);
2452 ID.AddInteger(RValueThis);
2453 ID.AddInteger(ConstThis);
2454 ID.AddInteger(VolatileThis);
2457 SpecialMemberOverloadResult *Result =
2458 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2460 // This was already cached
2464 Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
2465 Result = new (Result) SpecialMemberOverloadResult(ID);
2466 SpecialMemberCache.InsertNode(Result, InsertPoint);
2468 if (SM == CXXDestructor) {
2469 if (RD->needsImplicitDestructor())
2470 DeclareImplicitDestructor(RD);
2471 CXXDestructorDecl *DD = RD->getDestructor();
2472 assert(DD && "record without a destructor");
2473 Result->setMethod(DD);
2474 Result->setKind(DD->isDeleted() ?
2475 SpecialMemberOverloadResult::NoMemberOrDeleted :
2476 SpecialMemberOverloadResult::Success);
2480 // Prepare for overload resolution. Here we construct a synthetic argument
2481 // if necessary and make sure that implicit functions are declared.
2482 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2483 DeclarationName Name;
2487 QualType ArgType = CanTy;
2488 ExprValueKind VK = VK_LValue;
2490 if (SM == CXXDefaultConstructor) {
2491 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2493 if (RD->needsImplicitDefaultConstructor())
2494 DeclareImplicitDefaultConstructor(RD);
2496 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2497 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2498 if (RD->needsImplicitCopyConstructor())
2499 DeclareImplicitCopyConstructor(RD);
2500 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
2501 DeclareImplicitMoveConstructor(RD);
2503 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2504 if (RD->needsImplicitCopyAssignment())
2505 DeclareImplicitCopyAssignment(RD);
2506 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
2507 DeclareImplicitMoveAssignment(RD);
2513 ArgType.addVolatile();
2515 // This isn't /really/ specified by the standard, but it's implied
2516 // we should be working from an RValue in the case of move to ensure
2517 // that we prefer to bind to rvalue references, and an LValue in the
2518 // case of copy to ensure we don't bind to rvalue references.
2519 // Possibly an XValue is actually correct in the case of move, but
2520 // there is no semantic difference for class types in this restricted
2522 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2528 OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
2530 if (SM != CXXDefaultConstructor) {
2535 // Create the object argument
2536 QualType ThisTy = CanTy;
2540 ThisTy.addVolatile();
2541 Expr::Classification Classification =
2542 OpaqueValueExpr(SourceLocation(), ThisTy,
2543 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
2545 // Now we perform lookup on the name we computed earlier and do overload
2546 // resolution. Lookup is only performed directly into the class since there
2547 // will always be a (possibly implicit) declaration to shadow any others.
2548 OverloadCandidateSet OCS((SourceLocation()));
2549 DeclContext::lookup_result R = RD->lookup(Name);
2550 assert(!R.empty() &&
2551 "lookup for a constructor or assignment operator was empty");
2553 // Copy the candidates as our processing of them may load new declarations
2554 // from an external source and invalidate lookup_result.
2555 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2557 for (SmallVectorImpl<NamedDecl *>::iterator I = Candidates.begin(),
2558 E = Candidates.end();
2560 NamedDecl *Cand = *I;
2562 if (Cand->isInvalidDecl())
2565 if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
2566 // FIXME: [namespace.udecl]p15 says that we should only consider a
2567 // using declaration here if it does not match a declaration in the
2568 // derived class. We do not implement this correctly in other cases
2570 Cand = U->getTargetDecl();
2572 if (Cand->isInvalidDecl())
2576 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
2577 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2578 AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
2579 Classification, llvm::makeArrayRef(&Arg, NumArgs),
2582 AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
2583 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2584 } else if (FunctionTemplateDecl *Tmpl =
2585 dyn_cast<FunctionTemplateDecl>(Cand)) {
2586 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2587 AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2588 RD, 0, ThisTy, Classification,
2589 llvm::makeArrayRef(&Arg, NumArgs),
2592 AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
2593 0, llvm::makeArrayRef(&Arg, NumArgs),
2596 assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
2600 OverloadCandidateSet::iterator Best;
2601 switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
2603 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2604 Result->setKind(SpecialMemberOverloadResult::Success);
2608 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
2609 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2613 Result->setMethod(0);
2614 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
2617 case OR_No_Viable_Function:
2618 Result->setMethod(0);
2619 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2626 /// \brief Look up the default constructor for the given class.
2627 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
2628 SpecialMemberOverloadResult *Result =
2629 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
2632 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2635 /// \brief Look up the copying constructor for the given class.
2636 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
2638 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2639 "non-const, non-volatile qualifiers for copy ctor arg");
2640 SpecialMemberOverloadResult *Result =
2641 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
2642 Quals & Qualifiers::Volatile, false, false, false);
2644 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2647 /// \brief Look up the moving constructor for the given class.
2648 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
2650 SpecialMemberOverloadResult *Result =
2651 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
2652 Quals & Qualifiers::Volatile, false, false, false);
2654 return cast_or_null<CXXConstructorDecl>(Result->getMethod());
2657 /// \brief Look up the constructors for the given class.
2658 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2659 // If the implicit constructors have not yet been declared, do so now.
2660 if (CanDeclareSpecialMemberFunction(Class)) {
2661 if (Class->needsImplicitDefaultConstructor())
2662 DeclareImplicitDefaultConstructor(Class);
2663 if (Class->needsImplicitCopyConstructor())
2664 DeclareImplicitCopyConstructor(Class);
2665 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
2666 DeclareImplicitMoveConstructor(Class);
2669 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2670 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2671 return Class->lookup(Name);
2674 /// \brief Look up the copying assignment operator for the given class.
2675 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
2676 unsigned Quals, bool RValueThis,
2677 unsigned ThisQuals) {
2678 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2679 "non-const, non-volatile qualifiers for copy assignment arg");
2680 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2681 "non-const, non-volatile qualifiers for copy assignment this");
2682 SpecialMemberOverloadResult *Result =
2683 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
2684 Quals & Qualifiers::Volatile, RValueThis,
2685 ThisQuals & Qualifiers::Const,
2686 ThisQuals & Qualifiers::Volatile);
2688 return Result->getMethod();
2691 /// \brief Look up the moving assignment operator for the given class.
2692 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
2695 unsigned ThisQuals) {
2696 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
2697 "non-const, non-volatile qualifiers for copy assignment this");
2698 SpecialMemberOverloadResult *Result =
2699 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
2700 Quals & Qualifiers::Volatile, RValueThis,
2701 ThisQuals & Qualifiers::Const,
2702 ThisQuals & Qualifiers::Volatile);
2704 return Result->getMethod();
2707 /// \brief Look for the destructor of the given class.
2709 /// During semantic analysis, this routine should be used in lieu of
2710 /// CXXRecordDecl::getDestructor().
2712 /// \returns The destructor for this class.
2713 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2714 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
2715 false, false, false,
2716 false, false)->getMethod());
2719 /// LookupLiteralOperator - Determine which literal operator should be used for
2720 /// a user-defined literal, per C++11 [lex.ext].
2722 /// Normal overload resolution is not used to select which literal operator to
2723 /// call for a user-defined literal. Look up the provided literal operator name,
2724 /// and filter the results to the appropriate set for the given argument types.
2725 Sema::LiteralOperatorLookupResult
2726 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
2727 ArrayRef<QualType> ArgTys,
2728 bool AllowRaw, bool AllowTemplate,
2729 bool AllowStringTemplate) {
2731 assert(R.getResultKind() != LookupResult::Ambiguous &&
2732 "literal operator lookup can't be ambiguous");
2734 // Filter the lookup results appropriately.
2735 LookupResult::Filter F = R.makeFilter();
2737 bool FoundRaw = false;
2738 bool FoundTemplate = false;
2739 bool FoundStringTemplate = false;
2740 bool FoundExactMatch = false;
2742 while (F.hasNext()) {
2744 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2745 D = USD->getTargetDecl();
2747 // If the declaration we found is invalid, skip it.
2748 if (D->isInvalidDecl()) {
2754 bool IsTemplate = false;
2755 bool IsStringTemplate = false;
2756 bool IsExactMatch = false;
2758 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2759 if (FD->getNumParams() == 1 &&
2760 FD->getParamDecl(0)->getType()->getAs<PointerType>())
2762 else if (FD->getNumParams() == ArgTys.size()) {
2763 IsExactMatch = true;
2764 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
2765 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
2766 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
2767 IsExactMatch = false;
2773 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
2774 TemplateParameterList *Params = FD->getTemplateParameters();
2775 if (Params->size() == 1)
2778 IsStringTemplate = true;
2782 FoundExactMatch = true;
2784 AllowTemplate = false;
2785 AllowStringTemplate = false;
2786 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
2787 // Go through again and remove the raw and template decls we've
2790 FoundRaw = FoundTemplate = FoundStringTemplate = false;
2792 } else if (AllowRaw && IsRaw) {
2794 } else if (AllowTemplate && IsTemplate) {
2795 FoundTemplate = true;
2796 } else if (AllowStringTemplate && IsStringTemplate) {
2797 FoundStringTemplate = true;
2805 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
2806 // parameter type, that is used in preference to a raw literal operator
2807 // or literal operator template.
2808 if (FoundExactMatch)
2811 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
2812 // operator template, but not both.
2813 if (FoundRaw && FoundTemplate) {
2814 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
2815 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2817 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
2818 D = USD->getTargetDecl();
2819 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2820 D = FunTmpl->getTemplatedDecl();
2821 NoteOverloadCandidate(cast<FunctionDecl>(D));
2830 return LOLR_Template;
2832 if (FoundStringTemplate)
2833 return LOLR_StringTemplate;
2835 // Didn't find anything we could use.
2836 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
2837 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
2838 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
2839 << (AllowTemplate || AllowStringTemplate);
2843 void ADLResult::insert(NamedDecl *New) {
2844 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2846 // If we haven't yet seen a decl for this key, or the last decl
2847 // was exactly this one, we're done.
2848 if (Old == 0 || Old == New) {
2853 // Otherwise, decide which is a more recent redeclaration.
2854 FunctionDecl *OldFD, *NewFD;
2855 if (isa<FunctionTemplateDecl>(New)) {
2856 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2857 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2859 OldFD = cast<FunctionDecl>(Old);
2860 NewFD = cast<FunctionDecl>(New);
2863 FunctionDecl *Cursor = NewFD;
2865 Cursor = Cursor->getPreviousDecl();
2867 // If we got to the end without finding OldFD, OldFD is the newer
2868 // declaration; leave things as they are.
2869 if (!Cursor) return;
2871 // If we do find OldFD, then NewFD is newer.
2872 if (Cursor == OldFD) break;
2874 // Otherwise, keep looking.
2880 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2881 SourceLocation Loc, ArrayRef<Expr *> Args,
2882 ADLResult &Result) {
2883 // Find all of the associated namespaces and classes based on the
2884 // arguments we have.
2885 AssociatedNamespaceSet AssociatedNamespaces;
2886 AssociatedClassSet AssociatedClasses;
2887 FindAssociatedClassesAndNamespaces(Loc, Args,
2888 AssociatedNamespaces,
2893 T1 = Args[0]->getType();
2894 if (Args.size() >= 2)
2895 T2 = Args[1]->getType();
2898 // C++ [basic.lookup.argdep]p3:
2899 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2900 // and let Y be the lookup set produced by argument dependent
2901 // lookup (defined as follows). If X contains [...] then Y is
2902 // empty. Otherwise Y is the set of declarations found in the
2903 // namespaces associated with the argument types as described
2904 // below. The set of declarations found by the lookup of the name
2905 // is the union of X and Y.
2907 // Here, we compute Y and add its members to the overloaded
2909 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2910 NSEnd = AssociatedNamespaces.end();
2911 NS != NSEnd; ++NS) {
2912 // When considering an associated namespace, the lookup is the
2913 // same as the lookup performed when the associated namespace is
2914 // used as a qualifier (3.4.3.2) except that:
2916 // -- Any using-directives in the associated namespace are
2919 // -- Any namespace-scope friend functions declared in
2920 // associated classes are visible within their respective
2921 // namespaces even if they are not visible during an ordinary
2923 DeclContext::lookup_result R = (*NS)->lookup(Name);
2924 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
2927 // If the only declaration here is an ordinary friend, consider
2928 // it only if it was declared in an associated classes.
2929 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
2930 // If it's neither ordinarily visible nor a friend, we can't find it.
2931 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
2934 bool DeclaredInAssociatedClass = false;
2935 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
2936 DeclContext *LexDC = DI->getLexicalDeclContext();
2937 if (isa<CXXRecordDecl>(LexDC) &&
2938 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
2939 DeclaredInAssociatedClass = true;
2943 if (!DeclaredInAssociatedClass)
2947 if (isa<UsingShadowDecl>(D))
2948 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2950 if (isa<FunctionDecl>(D)) {
2952 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2955 } else if (!isa<FunctionTemplateDecl>(D))
2963 //----------------------------------------------------------------------------
2964 // Search for all visible declarations.
2965 //----------------------------------------------------------------------------
2966 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2968 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
2972 class ShadowContextRAII;
2974 class VisibleDeclsRecord {
2976 /// \brief An entry in the shadow map, which is optimized to store a
2977 /// single declaration (the common case) but can also store a list
2978 /// of declarations.
2979 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
2982 /// \brief A mapping from declaration names to the declarations that have
2983 /// this name within a particular scope.
2984 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2986 /// \brief A list of shadow maps, which is used to model name hiding.
2987 std::list<ShadowMap> ShadowMaps;
2989 /// \brief The declaration contexts we have already visited.
2990 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2992 friend class ShadowContextRAII;
2995 /// \brief Determine whether we have already visited this context
2996 /// (and, if not, note that we are going to visit that context now).
2997 bool visitedContext(DeclContext *Ctx) {
2998 return !VisitedContexts.insert(Ctx);
3001 bool alreadyVisitedContext(DeclContext *Ctx) {
3002 return VisitedContexts.count(Ctx);
3005 /// \brief Determine whether the given declaration is hidden in the
3008 /// \returns the declaration that hides the given declaration, or
3009 /// NULL if no such declaration exists.
3010 NamedDecl *checkHidden(NamedDecl *ND);
3012 /// \brief Add a declaration to the current shadow map.
3013 void add(NamedDecl *ND) {
3014 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3018 /// \brief RAII object that records when we've entered a shadow context.
3019 class ShadowContextRAII {
3020 VisibleDeclsRecord &Visible;
3022 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3025 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3026 Visible.ShadowMaps.push_back(ShadowMap());
3029 ~ShadowContextRAII() {
3030 Visible.ShadowMaps.pop_back();
3034 } // end anonymous namespace
3036 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3037 // Look through using declarations.
3038 ND = ND->getUnderlyingDecl();
3040 unsigned IDNS = ND->getIdentifierNamespace();
3041 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3042 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3043 SM != SMEnd; ++SM) {
3044 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3045 if (Pos == SM->end())
3048 for (ShadowMapEntry::iterator I = Pos->second.begin(),
3049 IEnd = Pos->second.end();
3051 // A tag declaration does not hide a non-tag declaration.
3052 if ((*I)->hasTagIdentifierNamespace() &&
3053 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
3054 Decl::IDNS_ObjCProtocol)))
3057 // Protocols are in distinct namespaces from everything else.
3058 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3059 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3060 (*I)->getIdentifierNamespace() != IDNS)
3063 // Functions and function templates in the same scope overload
3064 // rather than hide. FIXME: Look for hiding based on function
3066 if ((*I)->isFunctionOrFunctionTemplate() &&
3067 ND->isFunctionOrFunctionTemplate() &&
3068 SM == ShadowMaps.rbegin())
3071 // We've found a declaration that hides this one.
3079 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3080 bool QualifiedNameLookup,
3082 VisibleDeclConsumer &Consumer,
3083 VisibleDeclsRecord &Visited) {
3087 // Make sure we don't visit the same context twice.
3088 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3091 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3092 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3094 // Enumerate all of the results in this context.
3095 for (DeclContext::all_lookups_iterator L = Ctx->lookups_begin(),
3096 LEnd = Ctx->lookups_end();
3098 DeclContext::lookup_result R = *L;
3099 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
3101 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) {
3102 if ((ND = Result.getAcceptableDecl(ND))) {
3103 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3110 // Traverse using directives for qualified name lookup.
3111 if (QualifiedNameLookup) {
3112 ShadowContextRAII Shadow(Visited);
3113 DeclContext::udir_iterator I, E;
3114 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
3115 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
3116 QualifiedNameLookup, InBaseClass, Consumer, Visited);
3120 // Traverse the contexts of inherited C++ classes.
3121 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
3122 if (!Record->hasDefinition())
3125 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
3126 BEnd = Record->bases_end();
3128 QualType BaseType = B->getType();
3130 // Don't look into dependent bases, because name lookup can't look
3132 if (BaseType->isDependentType())
3135 const RecordType *Record = BaseType->getAs<RecordType>();
3139 // FIXME: It would be nice to be able to determine whether referencing
3140 // a particular member would be ambiguous. For example, given
3142 // struct A { int member; };
3143 // struct B { int member; };
3144 // struct C : A, B { };
3146 // void f(C *c) { c->### }
3148 // accessing 'member' would result in an ambiguity. However, we
3149 // could be smart enough to qualify the member with the base
3158 // Find results in this base class (and its bases).
3159 ShadowContextRAII Shadow(Visited);
3160 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
3161 true, Consumer, Visited);
3165 // Traverse the contexts of Objective-C classes.
3166 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3167 // Traverse categories.
3168 for (ObjCInterfaceDecl::visible_categories_iterator
3169 Cat = IFace->visible_categories_begin(),
3170 CatEnd = IFace->visible_categories_end();
3171 Cat != CatEnd; ++Cat) {
3172 ShadowContextRAII Shadow(Visited);
3173 LookupVisibleDecls(*Cat, Result, QualifiedNameLookup, false,
3177 // Traverse protocols.
3178 for (ObjCInterfaceDecl::all_protocol_iterator
3179 I = IFace->all_referenced_protocol_begin(),
3180 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
3181 ShadowContextRAII Shadow(Visited);
3182 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
3186 // Traverse the superclass.
3187 if (IFace->getSuperClass()) {
3188 ShadowContextRAII Shadow(Visited);
3189 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
3190 true, Consumer, Visited);
3193 // If there is an implementation, traverse it. We do this to find
3194 // synthesized ivars.
3195 if (IFace->getImplementation()) {
3196 ShadowContextRAII Shadow(Visited);
3197 LookupVisibleDecls(IFace->getImplementation(), Result,
3198 QualifiedNameLookup, InBaseClass, Consumer, Visited);
3200 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3201 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
3202 E = Protocol->protocol_end(); I != E; ++I) {
3203 ShadowContextRAII Shadow(Visited);
3204 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
3207 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3208 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
3209 E = Category->protocol_end(); I != E; ++I) {
3210 ShadowContextRAII Shadow(Visited);
3211 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
3215 // If there is an implementation, traverse it.
3216 if (Category->getImplementation()) {
3217 ShadowContextRAII Shadow(Visited);
3218 LookupVisibleDecls(Category->getImplementation(), Result,
3219 QualifiedNameLookup, true, Consumer, Visited);
3224 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3225 UnqualUsingDirectiveSet &UDirs,
3226 VisibleDeclConsumer &Consumer,
3227 VisibleDeclsRecord &Visited) {
3231 if (!S->getEntity() ||
3233 !Visited.alreadyVisitedContext(S->getEntity())) ||
3234 (S->getEntity())->isFunctionOrMethod()) {
3235 FindLocalExternScope FindLocals(Result);
3236 // Walk through the declarations in this Scope.
3237 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
3239 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
3240 if ((ND = Result.getAcceptableDecl(ND))) {
3241 Consumer.FoundDecl(ND, Visited.checkHidden(ND), 0, false);
3247 // FIXME: C++ [temp.local]p8
3248 DeclContext *Entity = 0;
3249 if (S->getEntity()) {
3250 // Look into this scope's declaration context, along with any of its
3251 // parent lookup contexts (e.g., enclosing classes), up to the point
3252 // where we hit the context stored in the next outer scope.
3253 Entity = S->getEntity();
3254 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3256 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3257 Ctx = Ctx->getLookupParent()) {
3258 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3259 if (Method->isInstanceMethod()) {
3260 // For instance methods, look for ivars in the method's interface.
3261 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3262 Result.getNameLoc(), Sema::LookupMemberName);
3263 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3264 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3265 /*InBaseClass=*/false, Consumer, Visited);
3269 // We've already performed all of the name lookup that we need
3270 // to for Objective-C methods; the next context will be the
3275 if (Ctx->isFunctionOrMethod())
3278 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3279 /*InBaseClass=*/false, Consumer, Visited);
3281 } else if (!S->getParent()) {
3282 // Look into the translation unit scope. We walk through the translation
3283 // unit's declaration context, because the Scope itself won't have all of
3284 // the declarations if we loaded a precompiled header.
3285 // FIXME: We would like the translation unit's Scope object to point to the
3286 // translation unit, so we don't need this special "if" branch. However,
3287 // doing so would force the normal C++ name-lookup code to look into the
3288 // translation unit decl when the IdentifierInfo chains would suffice.
3289 // Once we fix that problem (which is part of a more general "don't look
3290 // in DeclContexts unless we have to" optimization), we can eliminate this.
3291 Entity = Result.getSema().Context.getTranslationUnitDecl();
3292 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3293 /*InBaseClass=*/false, Consumer, Visited);
3297 // Lookup visible declarations in any namespaces found by using
3299 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
3300 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
3301 for (; UI != UEnd; ++UI)
3302 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
3303 Result, /*QualifiedNameLookup=*/false,
3304 /*InBaseClass=*/false, Consumer, Visited);
3307 // Lookup names in the parent scope.
3308 ShadowContextRAII Shadow(Visited);
3309 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3312 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3313 VisibleDeclConsumer &Consumer,
3314 bool IncludeGlobalScope) {
3315 // Determine the set of using directives available during
3316 // unqualified name lookup.
3318 UnqualUsingDirectiveSet UDirs;
3319 if (getLangOpts().CPlusPlus) {
3320 // Find the first namespace or translation-unit scope.
3321 while (S && !isNamespaceOrTranslationUnitScope(S))
3324 UDirs.visitScopeChain(Initial, S);
3328 // Look for visible declarations.
3329 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3330 Result.setAllowHidden(Consumer.includeHiddenDecls());
3331 VisibleDeclsRecord Visited;
3332 if (!IncludeGlobalScope)
3333 Visited.visitedContext(Context.getTranslationUnitDecl());
3334 ShadowContextRAII Shadow(Visited);
3335 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3338 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3339 VisibleDeclConsumer &Consumer,
3340 bool IncludeGlobalScope) {
3341 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3342 Result.setAllowHidden(Consumer.includeHiddenDecls());
3343 VisibleDeclsRecord Visited;
3344 if (!IncludeGlobalScope)
3345 Visited.visitedContext(Context.getTranslationUnitDecl());
3346 ShadowContextRAII Shadow(Visited);
3347 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3348 /*InBaseClass=*/false, Consumer, Visited);
3351 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3352 /// If GnuLabelLoc is a valid source location, then this is a definition
3353 /// of an __label__ label name, otherwise it is a normal label definition
3355 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3356 SourceLocation GnuLabelLoc) {
3357 // Do a lookup to see if we have a label with this name already.
3360 if (GnuLabelLoc.isValid()) {
3361 // Local label definitions always shadow existing labels.
3362 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3363 Scope *S = CurScope;
3364 PushOnScopeChains(Res, S, true);
3365 return cast<LabelDecl>(Res);
3368 // Not a GNU local label.
3369 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3370 // If we found a label, check to see if it is in the same context as us.
3371 // When in a Block, we don't want to reuse a label in an enclosing function.
3372 if (Res && Res->getDeclContext() != CurContext)
3375 // If not forward referenced or defined already, create the backing decl.
3376 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3377 Scope *S = CurScope->getFnParent();
3378 assert(S && "Not in a function?");
3379 PushOnScopeChains(Res, S, true);
3381 return cast<LabelDecl>(Res);
3384 //===----------------------------------------------------------------------===//
3386 //===----------------------------------------------------------------------===//
3390 typedef SmallVector<TypoCorrection, 1> TypoResultList;
3391 typedef llvm::StringMap<TypoResultList, llvm::BumpPtrAllocator> TypoResultsMap;
3392 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
3394 static const unsigned MaxTypoDistanceResultSets = 5;
3396 class TypoCorrectionConsumer : public VisibleDeclConsumer {
3397 /// \brief The name written that is a typo in the source.
3400 /// \brief The results found that have the smallest edit distance
3401 /// found (so far) with the typo name.
3403 /// The pointer value being set to the current DeclContext indicates
3404 /// whether there is a keyword with this name.
3405 TypoEditDistanceMap CorrectionResults;
3410 explicit TypoCorrectionConsumer(Sema &SemaRef, IdentifierInfo *Typo)
3411 : Typo(Typo->getName()),
3414 bool includeHiddenDecls() const { return true; }
3416 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
3418 void FoundName(StringRef Name);
3419 void addKeywordResult(StringRef Keyword);
3420 void addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS = NULL,
3421 bool isKeyword = false);
3422 void addCorrection(TypoCorrection Correction);
3424 typedef TypoResultsMap::iterator result_iterator;
3425 typedef TypoEditDistanceMap::iterator distance_iterator;
3426 distance_iterator begin() { return CorrectionResults.begin(); }
3427 distance_iterator end() { return CorrectionResults.end(); }
3428 void erase(distance_iterator I) { CorrectionResults.erase(I); }
3429 unsigned size() const { return CorrectionResults.size(); }
3430 bool empty() const { return CorrectionResults.empty(); }
3432 TypoResultList &operator[](StringRef Name) {
3433 return CorrectionResults.begin()->second[Name];
3436 unsigned getBestEditDistance(bool Normalized) {
3437 if (CorrectionResults.empty())
3438 return (std::numeric_limits<unsigned>::max)();
3440 unsigned BestED = CorrectionResults.begin()->first;
3441 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
3444 TypoResultsMap &getBestResults() {
3445 return CorrectionResults.begin()->second;
3452 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3453 DeclContext *Ctx, bool InBaseClass) {
3454 // Don't consider hidden names for typo correction.
3458 // Only consider entities with identifiers for names, ignoring
3459 // special names (constructors, overloaded operators, selectors,
3461 IdentifierInfo *Name = ND->getIdentifier();
3465 // Only consider visible declarations and declarations from modules with
3466 // names that exactly match.
3467 if (!LookupResult::isVisible(SemaRef, ND) && Name->getName() != Typo &&
3468 !findAcceptableDecl(SemaRef, ND))
3471 FoundName(Name->getName());
3474 void TypoCorrectionConsumer::FoundName(StringRef Name) {
3475 // Compute the edit distance between the typo and the name of this
3476 // entity, and add the identifier to the list of results.
3477 addName(Name, NULL);
3480 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3481 // Compute the edit distance between the typo and this keyword,
3482 // and add the keyword to the list of results.
3483 addName(Keyword, NULL, NULL, true);
3486 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3487 NestedNameSpecifier *NNS, bool isKeyword) {
3488 // Use a simple length-based heuristic to determine the minimum possible
3489 // edit distance. If the minimum isn't good enough, bail out early.
3490 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
3491 if (MinED && Typo.size() / MinED < 3)
3494 // Compute an upper bound on the allowable edit distance, so that the
3495 // edit-distance algorithm can short-circuit.
3496 unsigned UpperBound = (Typo.size() + 2) / 3 + 1;
3497 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
3498 if (ED >= UpperBound) return;
3500 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
3501 if (isKeyword) TC.makeKeyword();
3505 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3506 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3507 TypoResultList &CList =
3508 CorrectionResults[Correction.getEditDistance(false)][Name];
3510 if (!CList.empty() && !CList.back().isResolved())
3512 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
3513 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
3514 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
3515 RI != RIEnd; ++RI) {
3516 // If the Correction refers to a decl already in the result list,
3517 // replace the existing result if the string representation of Correction
3518 // comes before the current result alphabetically, then stop as there is
3519 // nothing more to be done to add Correction to the candidate set.
3520 if (RI->getCorrectionDecl() == NewND) {
3521 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
3527 if (CList.empty() || Correction.isResolved())
3528 CList.push_back(Correction);
3530 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
3531 erase(llvm::prior(CorrectionResults.end()));
3534 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
3535 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3536 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3537 static void getNestedNameSpecifierIdentifiers(
3538 NestedNameSpecifier *NNS,
3539 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3540 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
3541 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3543 Identifiers.clear();
3545 const IdentifierInfo *II = NULL;
3547 switch (NNS->getKind()) {
3548 case NestedNameSpecifier::Identifier:
3549 II = NNS->getAsIdentifier();
3552 case NestedNameSpecifier::Namespace:
3553 if (NNS->getAsNamespace()->isAnonymousNamespace())
3555 II = NNS->getAsNamespace()->getIdentifier();
3558 case NestedNameSpecifier::NamespaceAlias:
3559 II = NNS->getAsNamespaceAlias()->getIdentifier();
3562 case NestedNameSpecifier::TypeSpecWithTemplate:
3563 case NestedNameSpecifier::TypeSpec:
3564 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3567 case NestedNameSpecifier::Global:
3572 Identifiers.push_back(II);
3577 class SpecifierInfo {
3579 DeclContext* DeclCtx;
3580 NestedNameSpecifier* NameSpecifier;
3581 unsigned EditDistance;
3583 SpecifierInfo(DeclContext *Ctx, NestedNameSpecifier *NNS, unsigned ED)
3584 : DeclCtx(Ctx), NameSpecifier(NNS), EditDistance(ED) {}
3587 typedef SmallVector<DeclContext*, 4> DeclContextList;
3588 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
3590 class NamespaceSpecifierSet {
3591 ASTContext &Context;
3592 DeclContextList CurContextChain;
3593 std::string CurNameSpecifier;
3594 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
3595 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
3598 SpecifierInfoList Specifiers;
3599 llvm::SmallSetVector<unsigned, 4> Distances;
3600 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
3602 /// \brief Helper for building the list of DeclContexts between the current
3603 /// context and the top of the translation unit
3604 static DeclContextList BuildContextChain(DeclContext *Start);
3606 void SortNamespaces();
3609 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
3610 CXXScopeSpec *CurScopeSpec)
3611 : Context(Context), CurContextChain(BuildContextChain(CurContext)),
3613 if (NestedNameSpecifier *NNS =
3614 CurScopeSpec ? CurScopeSpec->getScopeRep() : 0) {
3615 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
3616 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3618 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
3620 // Build the list of identifiers that would be used for an absolute
3621 // (from the global context) NestedNameSpecifier referring to the current
3623 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3624 CEnd = CurContextChain.rend();
3626 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
3627 CurContextIdentifiers.push_back(ND->getIdentifier());
3630 // Add the global context as a NestedNameSpecifier
3631 Distances.insert(1);
3632 DistanceMap[1].push_back(
3633 SpecifierInfo(cast<DeclContext>(Context.getTranslationUnitDecl()),
3634 NestedNameSpecifier::GlobalSpecifier(Context), 1));
3637 /// \brief Add the DeclContext (a namespace or record) to the set, computing
3638 /// the corresponding NestedNameSpecifier and its distance in the process.
3639 void AddNameSpecifier(DeclContext *Ctx);
3641 typedef SpecifierInfoList::iterator iterator;
3643 if (!isSorted) SortNamespaces();
3644 return Specifiers.begin();
3646 iterator end() { return Specifiers.end(); }
3651 DeclContextList NamespaceSpecifierSet::BuildContextChain(DeclContext *Start) {
3652 assert(Start && "Building a context chain from a null context");
3653 DeclContextList Chain;
3654 for (DeclContext *DC = Start->getPrimaryContext(); DC != NULL;
3655 DC = DC->getLookupParent()) {
3656 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
3657 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
3658 !(ND && ND->isAnonymousNamespace()))
3659 Chain.push_back(DC->getPrimaryContext());
3664 void NamespaceSpecifierSet::SortNamespaces() {
3665 SmallVector<unsigned, 4> sortedDistances;
3666 sortedDistances.append(Distances.begin(), Distances.end());
3668 if (sortedDistances.size() > 1)
3669 std::sort(sortedDistances.begin(), sortedDistances.end());
3672 for (SmallVectorImpl<unsigned>::iterator DI = sortedDistances.begin(),
3673 DIEnd = sortedDistances.end();
3674 DI != DIEnd; ++DI) {
3675 SpecifierInfoList &SpecList = DistanceMap[*DI];
3676 Specifiers.append(SpecList.begin(), SpecList.end());
3682 static unsigned BuildNestedNameSpecifier(ASTContext &Context,
3683 DeclContextList &DeclChain,
3684 NestedNameSpecifier *&NNS) {
3685 unsigned NumSpecifiers = 0;
3686 for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
3687 CEnd = DeclChain.rend();
3689 if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
3690 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
3692 } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
3693 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
3694 RD->getTypeForDecl());
3698 return NumSpecifiers;
3701 void NamespaceSpecifierSet::AddNameSpecifier(DeclContext *Ctx) {
3702 NestedNameSpecifier *NNS = NULL;
3703 unsigned NumSpecifiers = 0;
3704 DeclContextList NamespaceDeclChain(BuildContextChain(Ctx));
3705 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
3707 // Eliminate common elements from the two DeclContext chains.
3708 for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
3709 CEnd = CurContextChain.rend();
3710 C != CEnd && !NamespaceDeclChain.empty() &&
3711 NamespaceDeclChain.back() == *C; ++C) {
3712 NamespaceDeclChain.pop_back();
3715 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
3716 NumSpecifiers = BuildNestedNameSpecifier(Context, NamespaceDeclChain, NNS);
3718 // Add an explicit leading '::' specifier if needed.
3719 if (NamespaceDeclChain.empty()) {
3720 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3721 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3723 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
3724 } else if (NamedDecl *ND =
3725 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
3726 IdentifierInfo *Name = ND->getIdentifier();
3727 bool SameNameSpecifier = false;
3728 if (std::find(CurNameSpecifierIdentifiers.begin(),
3729 CurNameSpecifierIdentifiers.end(),
3730 Name) != CurNameSpecifierIdentifiers.end()) {
3731 std::string NewNameSpecifier;
3732 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
3733 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
3734 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3735 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
3736 SpecifierOStream.flush();
3737 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
3739 if (SameNameSpecifier ||
3740 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
3741 Name) != CurContextIdentifiers.end()) {
3742 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
3743 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
3745 BuildNestedNameSpecifier(Context, FullNamespaceDeclChain, NNS);
3749 // If the built NestedNameSpecifier would be replacing an existing
3750 // NestedNameSpecifier, use the number of component identifiers that
3751 // would need to be changed as the edit distance instead of the number
3752 // of components in the built NestedNameSpecifier.
3753 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
3754 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
3755 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
3756 NumSpecifiers = llvm::ComputeEditDistance(
3757 ArrayRef<const IdentifierInfo *>(CurNameSpecifierIdentifiers),
3758 ArrayRef<const IdentifierInfo *>(NewNameSpecifierIdentifiers));
3762 Distances.insert(NumSpecifiers);
3763 DistanceMap[NumSpecifiers].push_back(SpecifierInfo(Ctx, NNS, NumSpecifiers));
3766 /// \brief Perform name lookup for a possible result for typo correction.
3767 static void LookupPotentialTypoResult(Sema &SemaRef,
3769 IdentifierInfo *Name,
3770 Scope *S, CXXScopeSpec *SS,
3771 DeclContext *MemberContext,
3772 bool EnteringContext,
3773 bool isObjCIvarLookup,
3775 Res.suppressDiagnostics();
3777 Res.setLookupName(Name);
3778 Res.setAllowHidden(FindHidden);
3779 if (MemberContext) {
3780 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
3781 if (isObjCIvarLookup) {
3782 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
3789 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
3796 SemaRef.LookupQualifiedName(Res, MemberContext);
3800 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
3803 // Fake ivar lookup; this should really be part of
3804 // LookupParsedName.
3805 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
3806 if (Method->isInstanceMethod() && Method->getClassInterface() &&
3808 (Res.isSingleResult() &&
3809 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
3810 if (ObjCIvarDecl *IV
3811 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
3819 /// \brief Add keywords to the consumer as possible typo corrections.
3820 static void AddKeywordsToConsumer(Sema &SemaRef,
3821 TypoCorrectionConsumer &Consumer,
3822 Scope *S, CorrectionCandidateCallback &CCC,
3823 bool AfterNestedNameSpecifier) {
3824 if (AfterNestedNameSpecifier) {
3825 // For 'X::', we know exactly which keywords can appear next.
3826 Consumer.addKeywordResult("template");
3827 if (CCC.WantExpressionKeywords)
3828 Consumer.addKeywordResult("operator");
3832 if (CCC.WantObjCSuper)
3833 Consumer.addKeywordResult("super");
3835 if (CCC.WantTypeSpecifiers) {
3836 // Add type-specifier keywords to the set of results.
3837 static const char *const CTypeSpecs[] = {
3838 "char", "const", "double", "enum", "float", "int", "long", "short",
3839 "signed", "struct", "union", "unsigned", "void", "volatile",
3840 "_Complex", "_Imaginary",
3841 // storage-specifiers as well
3842 "extern", "inline", "static", "typedef"
3845 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
3846 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3847 Consumer.addKeywordResult(CTypeSpecs[I]);
3849 if (SemaRef.getLangOpts().C99)
3850 Consumer.addKeywordResult("restrict");
3851 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
3852 Consumer.addKeywordResult("bool");
3853 else if (SemaRef.getLangOpts().C99)
3854 Consumer.addKeywordResult("_Bool");
3856 if (SemaRef.getLangOpts().CPlusPlus) {
3857 Consumer.addKeywordResult("class");
3858 Consumer.addKeywordResult("typename");
3859 Consumer.addKeywordResult("wchar_t");
3861 if (SemaRef.getLangOpts().CPlusPlus11) {
3862 Consumer.addKeywordResult("char16_t");
3863 Consumer.addKeywordResult("char32_t");
3864 Consumer.addKeywordResult("constexpr");
3865 Consumer.addKeywordResult("decltype");
3866 Consumer.addKeywordResult("thread_local");
3870 if (SemaRef.getLangOpts().GNUMode)
3871 Consumer.addKeywordResult("typeof");
3874 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
3875 Consumer.addKeywordResult("const_cast");
3876 Consumer.addKeywordResult("dynamic_cast");
3877 Consumer.addKeywordResult("reinterpret_cast");
3878 Consumer.addKeywordResult("static_cast");
3881 if (CCC.WantExpressionKeywords) {
3882 Consumer.addKeywordResult("sizeof");
3883 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
3884 Consumer.addKeywordResult("false");
3885 Consumer.addKeywordResult("true");
3888 if (SemaRef.getLangOpts().CPlusPlus) {
3889 static const char *const CXXExprs[] = {
3890 "delete", "new", "operator", "throw", "typeid"
3892 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
3893 for (unsigned I = 0; I != NumCXXExprs; ++I)
3894 Consumer.addKeywordResult(CXXExprs[I]);
3896 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
3897 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
3898 Consumer.addKeywordResult("this");
3900 if (SemaRef.getLangOpts().CPlusPlus11) {
3901 Consumer.addKeywordResult("alignof");
3902 Consumer.addKeywordResult("nullptr");
3906 if (SemaRef.getLangOpts().C11) {
3907 // FIXME: We should not suggest _Alignof if the alignof macro
3909 Consumer.addKeywordResult("_Alignof");
3913 if (CCC.WantRemainingKeywords) {
3914 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
3916 static const char *const CStmts[] = {
3917 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3918 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
3919 for (unsigned I = 0; I != NumCStmts; ++I)
3920 Consumer.addKeywordResult(CStmts[I]);
3922 if (SemaRef.getLangOpts().CPlusPlus) {
3923 Consumer.addKeywordResult("catch");
3924 Consumer.addKeywordResult("try");
3927 if (S && S->getBreakParent())
3928 Consumer.addKeywordResult("break");
3930 if (S && S->getContinueParent())
3931 Consumer.addKeywordResult("continue");
3933 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
3934 Consumer.addKeywordResult("case");
3935 Consumer.addKeywordResult("default");
3938 if (SemaRef.getLangOpts().CPlusPlus) {
3939 Consumer.addKeywordResult("namespace");
3940 Consumer.addKeywordResult("template");
3943 if (S && S->isClassScope()) {
3944 Consumer.addKeywordResult("explicit");
3945 Consumer.addKeywordResult("friend");
3946 Consumer.addKeywordResult("mutable");
3947 Consumer.addKeywordResult("private");
3948 Consumer.addKeywordResult("protected");
3949 Consumer.addKeywordResult("public");
3950 Consumer.addKeywordResult("virtual");
3954 if (SemaRef.getLangOpts().CPlusPlus) {
3955 Consumer.addKeywordResult("using");
3957 if (SemaRef.getLangOpts().CPlusPlus11)
3958 Consumer.addKeywordResult("static_assert");
3963 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3964 TypoCorrection &Candidate) {
3965 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3966 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3969 /// \brief Check whether the declarations found for a typo correction are
3970 /// visible, and if none of them are, convert the correction to an 'import
3971 /// a module' correction.
3972 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC,
3973 DeclarationName TypoName) {
3974 if (TC.begin() == TC.end())
3977 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3979 for (/**/; DI != DE; ++DI)
3980 if (!LookupResult::isVisible(SemaRef, *DI))
3982 // Nothing to do if all decls are visible.
3986 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3987 bool AnyVisibleDecls = !NewDecls.empty();
3989 for (/**/; DI != DE; ++DI) {
3990 NamedDecl *VisibleDecl = *DI;
3991 if (!LookupResult::isVisible(SemaRef, *DI))
3992 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3995 if (!AnyVisibleDecls) {
3996 // Found a visible decl, discard all hidden ones.
3997 AnyVisibleDecls = true;
4000 NewDecls.push_back(VisibleDecl);
4001 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4002 NewDecls.push_back(*DI);
4005 if (NewDecls.empty())
4006 TC = TypoCorrection();
4008 TC.setCorrectionDecls(NewDecls);
4009 TC.setRequiresImport(!AnyVisibleDecls);
4013 /// \brief Try to "correct" a typo in the source code by finding
4014 /// visible declarations whose names are similar to the name that was
4015 /// present in the source code.
4017 /// \param TypoName the \c DeclarationNameInfo structure that contains
4018 /// the name that was present in the source code along with its location.
4020 /// \param LookupKind the name-lookup criteria used to search for the name.
4022 /// \param S the scope in which name lookup occurs.
4024 /// \param SS the nested-name-specifier that precedes the name we're
4025 /// looking for, if present.
4027 /// \param CCC A CorrectionCandidateCallback object that provides further
4028 /// validation of typo correction candidates. It also provides flags for
4029 /// determining the set of keywords permitted.
4031 /// \param MemberContext if non-NULL, the context in which to look for
4032 /// a member access expression.
4034 /// \param EnteringContext whether we're entering the context described by
4035 /// the nested-name-specifier SS.
4037 /// \param OPT when non-NULL, the search for visible declarations will
4038 /// also walk the protocols in the qualified interfaces of \p OPT.
4040 /// \returns a \c TypoCorrection containing the corrected name if the typo
4041 /// along with information such as the \c NamedDecl where the corrected name
4042 /// was declared, and any additional \c NestedNameSpecifier needed to access
4043 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4044 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4045 Sema::LookupNameKind LookupKind,
4046 Scope *S, CXXScopeSpec *SS,
4047 CorrectionCandidateCallback &CCC,
4048 DeclContext *MemberContext,
4049 bool EnteringContext,
4050 const ObjCObjectPointerType *OPT,
4051 bool RecordFailure) {
4052 // Always let the ExternalSource have the first chance at correction, even
4053 // if we would otherwise have given up.
4054 if (ExternalSource) {
4055 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4056 TypoName, LookupKind, S, SS, CCC, MemberContext, EnteringContext, OPT))
4060 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4061 DisableTypoCorrection)
4062 return TypoCorrection();
4064 // In Microsoft mode, don't perform typo correction in a template member
4065 // function dependent context because it interferes with the "lookup into
4066 // dependent bases of class templates" feature.
4067 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
4068 isa<CXXMethodDecl>(CurContext))
4069 return TypoCorrection();
4071 // We only attempt to correct typos for identifiers.
4072 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4074 return TypoCorrection();
4076 // If the scope specifier itself was invalid, don't try to correct
4078 if (SS && SS->isInvalid())
4079 return TypoCorrection();
4081 // Never try to correct typos during template deduction or
4083 if (!ActiveTemplateInstantiations.empty())
4084 return TypoCorrection();
4086 // Don't try to correct 'super'.
4087 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4088 return TypoCorrection();
4090 // Abort if typo correction already failed for this specific typo.
4091 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4092 if (locs != TypoCorrectionFailures.end() &&
4093 locs->second.count(TypoName.getLoc()))
4094 return TypoCorrection();
4096 // Don't try to correct the identifier "vector" when in AltiVec mode.
4097 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4098 // remove this workaround.
4099 if (getLangOpts().AltiVec && Typo->isStr("vector"))
4100 return TypoCorrection();
4102 NamespaceSpecifierSet Namespaces(Context, CurContext, SS);
4104 TypoCorrectionConsumer Consumer(*this, Typo);
4106 // If a callback object considers an empty typo correction candidate to be
4107 // viable, assume it does not do any actual validation of the candidates.
4108 TypoCorrection EmptyCorrection;
4109 bool ValidatingCallback = !isCandidateViable(CCC, EmptyCorrection);
4111 // Perform name lookup to find visible, similarly-named entities.
4112 bool IsUnqualifiedLookup = false;
4113 DeclContext *QualifiedDC = MemberContext;
4114 if (MemberContext) {
4115 LookupVisibleDecls(MemberContext, LookupKind, Consumer);
4117 // Look in qualified interfaces.
4119 for (ObjCObjectPointerType::qual_iterator
4120 I = OPT->qual_begin(), E = OPT->qual_end();
4122 LookupVisibleDecls(*I, LookupKind, Consumer);
4124 } else if (SS && SS->isSet()) {
4125 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4127 return TypoCorrection();
4129 // Provide a stop gap for files that are just seriously broken. Trying
4130 // to correct all typos can turn into a HUGE performance penalty, causing
4131 // some files to take minutes to get rejected by the parser.
4132 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
4133 return TypoCorrection();
4136 LookupVisibleDecls(QualifiedDC, LookupKind, Consumer);
4138 IsUnqualifiedLookup = true;
4139 UnqualifiedTyposCorrectedMap::iterator Cached
4140 = UnqualifiedTyposCorrected.find(Typo);
4141 if (Cached != UnqualifiedTyposCorrected.end()) {
4142 // Add the cached value, unless it's a keyword or fails validation. In the
4143 // keyword case, we'll end up adding the keyword below.
4144 if (Cached->second) {
4145 if (!Cached->second.isKeyword() &&
4146 isCandidateViable(CCC, Cached->second)) {
4147 // Do not use correction that is unaccessible in the given scope.
4148 NamedDecl *CorrectionDecl = Cached->second.getCorrectionDecl();
4149 DeclarationNameInfo NameInfo(CorrectionDecl->getDeclName(),
4150 CorrectionDecl->getLocation());
4151 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4152 if (LookupName(R, S))
4153 Consumer.addCorrection(Cached->second);
4156 // Only honor no-correction cache hits when a callback that will validate
4157 // correction candidates is not being used.
4158 if (!ValidatingCallback)
4159 return TypoCorrection();
4162 if (Cached == UnqualifiedTyposCorrected.end()) {
4163 // Provide a stop gap for files that are just seriously broken. Trying
4164 // to correct all typos can turn into a HUGE performance penalty, causing
4165 // some files to take minutes to get rejected by the parser.
4166 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
4167 return TypoCorrection();
4171 // Determine whether we are going to search in the various namespaces for
4173 bool SearchNamespaces
4174 = getLangOpts().CPlusPlus &&
4175 (IsUnqualifiedLookup || (SS && SS->isSet()));
4176 // In a few cases we *only* want to search for corrections based on just
4177 // adding or changing the nested name specifier.
4178 unsigned TypoLen = Typo->getName().size();
4179 bool AllowOnlyNNSChanges = TypoLen < 3;
4181 if (IsUnqualifiedLookup || SearchNamespaces) {
4182 // For unqualified lookup, look through all of the names that we have
4183 // seen in this translation unit.
4184 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4185 for (IdentifierTable::iterator I = Context.Idents.begin(),
4186 IEnd = Context.Idents.end();
4188 Consumer.FoundName(I->getKey());
4190 // Walk through identifiers in external identifier sources.
4191 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4192 if (IdentifierInfoLookup *External
4193 = Context.Idents.getExternalIdentifierLookup()) {
4194 OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
4196 StringRef Name = Iter->Next();
4200 Consumer.FoundName(Name);
4205 AddKeywordsToConsumer(*this, Consumer, S, CCC, SS && SS->isNotEmpty());
4207 // If we haven't found anything, we're done.
4208 if (Consumer.empty())
4209 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4210 IsUnqualifiedLookup);
4212 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4213 // is not more that about a third of the length of the typo's identifier.
4214 unsigned ED = Consumer.getBestEditDistance(true);
4215 if (ED > 0 && TypoLen / ED < 3)
4216 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4217 IsUnqualifiedLookup);
4219 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4220 // to search those namespaces.
4221 if (SearchNamespaces) {
4222 // Load any externally-known namespaces.
4223 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4224 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4225 LoadedExternalKnownNamespaces = true;
4226 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4227 for (unsigned I = 0, N = ExternalKnownNamespaces.size(); I != N; ++I)
4228 KnownNamespaces[ExternalKnownNamespaces[I]] = true;
4231 for (llvm::MapVector<NamespaceDecl*, bool>::iterator
4232 KNI = KnownNamespaces.begin(),
4233 KNIEnd = KnownNamespaces.end();
4234 KNI != KNIEnd; ++KNI)
4235 Namespaces.AddNameSpecifier(KNI->first);
4237 for (ASTContext::type_iterator TI = Context.types_begin(),
4238 TIEnd = Context.types_end();
4239 TI != TIEnd; ++TI) {
4240 if (CXXRecordDecl *CD = (*TI)->getAsCXXRecordDecl()) {
4241 CD = CD->getCanonicalDecl();
4242 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4244 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4245 Namespaces.AddNameSpecifier(CD);
4250 // Weed out any names that could not be found by name lookup or, if a
4251 // CorrectionCandidateCallback object was provided, failed validation.
4252 SmallVector<TypoCorrection, 16> QualifiedResults;
4253 LookupResult TmpRes(*this, TypoName, LookupKind);
4254 TmpRes.suppressDiagnostics();
4255 while (!Consumer.empty()) {
4256 TypoCorrectionConsumer::distance_iterator DI = Consumer.begin();
4257 for (TypoCorrectionConsumer::result_iterator I = DI->second.begin(),
4258 IEnd = DI->second.end();
4259 I != IEnd; /* Increment in loop. */) {
4260 // If we only want nested name specifier corrections, ignore potential
4261 // corrections that have a different base identifier from the typo.
4262 if (AllowOnlyNNSChanges &&
4263 I->second.front().getCorrectionAsIdentifierInfo() != Typo) {
4264 TypoCorrectionConsumer::result_iterator Prev = I;
4266 DI->second.erase(Prev);
4270 // If the item already has been looked up or is a keyword, keep it.
4271 // If a validator callback object was given, drop the correction
4272 // unless it passes validation.
4273 bool Viable = false;
4274 for (TypoResultList::iterator RI = I->second.begin();
4275 RI != I->second.end(); /* Increment in loop. */) {
4276 TypoResultList::iterator Prev = RI;
4278 if (Prev->isResolved()) {
4279 if (!isCandidateViable(CCC, *Prev))
4280 RI = I->second.erase(Prev);
4285 if (Viable || I->second.empty()) {
4286 TypoCorrectionConsumer::result_iterator Prev = I;
4289 DI->second.erase(Prev);
4292 assert(I->second.size() == 1 && "Expected a single unresolved candidate");
4294 // Perform name lookup on this name.
4295 TypoCorrection &Candidate = I->second.front();
4296 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4297 DeclContext *TempMemberContext = MemberContext;
4298 CXXScopeSpec *TempSS = SS;
4300 LookupPotentialTypoResult(*this, TmpRes, Name, S, TempSS,
4301 TempMemberContext, EnteringContext,
4302 CCC.IsObjCIvarLookup,
4303 Name == TypoName.getName() &&
4304 !Candidate.WillReplaceSpecifier());
4306 switch (TmpRes.getResultKind()) {
4307 case LookupResult::NotFound:
4308 case LookupResult::NotFoundInCurrentInstantiation:
4309 case LookupResult::FoundUnresolvedValue:
4311 // Immediately retry the lookup without the given CXXScopeSpec
4313 Candidate.WillReplaceSpecifier(true);
4316 if (TempMemberContext) {
4319 TempMemberContext = NULL;
4322 QualifiedResults.push_back(Candidate);
4323 // We didn't find this name in our scope, or didn't like what we found;
4326 TypoCorrectionConsumer::result_iterator Next = I;
4328 DI->second.erase(I);
4333 case LookupResult::Ambiguous:
4334 // We don't deal with ambiguities.
4335 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4337 case LookupResult::FoundOverloaded: {
4338 TypoCorrectionConsumer::result_iterator Prev = I;
4339 // Store all of the Decls for overloaded symbols
4340 for (LookupResult::iterator TRD = TmpRes.begin(),
4341 TRDEnd = TmpRes.end();
4342 TRD != TRDEnd; ++TRD)
4343 Candidate.addCorrectionDecl(*TRD);
4345 if (!isCandidateViable(CCC, Candidate)) {
4346 QualifiedResults.push_back(Candidate);
4347 DI->second.erase(Prev);
4352 case LookupResult::Found: {
4353 TypoCorrectionConsumer::result_iterator Prev = I;
4354 Candidate.setCorrectionDecl(TmpRes.getAsSingle<NamedDecl>());
4356 if (!isCandidateViable(CCC, Candidate)) {
4357 QualifiedResults.push_back(Candidate);
4358 DI->second.erase(Prev);
4366 if (DI->second.empty())
4368 else if (!getLangOpts().CPlusPlus || QualifiedResults.empty() || !DI->first)
4369 // If there are results in the closest possible bucket, stop
4372 // Only perform the qualified lookups for C++
4373 if (SearchNamespaces) {
4374 TmpRes.suppressDiagnostics();
4375 for (SmallVector<TypoCorrection,
4376 16>::iterator QRI = QualifiedResults.begin(),
4377 QRIEnd = QualifiedResults.end();
4378 QRI != QRIEnd; ++QRI) {
4379 for (NamespaceSpecifierSet::iterator NI = Namespaces.begin(),
4380 NIEnd = Namespaces.end();
4381 NI != NIEnd; ++NI) {
4382 DeclContext *Ctx = NI->DeclCtx;
4383 const Type *NSType = NI->NameSpecifier->getAsType();
4385 // If the current NestedNameSpecifier refers to a class and the
4386 // current correction candidate is the name of that class, then skip
4387 // it as it is unlikely a qualified version of the class' constructor
4388 // is an appropriate correction.
4389 if (CXXRecordDecl *NSDecl =
4390 NSType ? NSType->getAsCXXRecordDecl() : 0) {
4391 if (NSDecl->getIdentifier() == QRI->getCorrectionAsIdentifierInfo())
4395 TypoCorrection TC(*QRI);
4396 TC.ClearCorrectionDecls();
4397 TC.setCorrectionSpecifier(NI->NameSpecifier);
4398 TC.setQualifierDistance(NI->EditDistance);
4399 TC.setCallbackDistance(0); // Reset the callback distance
4401 // If the current correction candidate and namespace combination are
4402 // too far away from the original typo based on the normalized edit
4403 // distance, then skip performing a qualified name lookup.
4404 unsigned TmpED = TC.getEditDistance(true);
4405 if (QRI->getCorrectionAsIdentifierInfo() != Typo &&
4406 TmpED && TypoLen / TmpED < 3)
4410 TmpRes.setLookupName(QRI->getCorrectionAsIdentifierInfo());
4411 if (!LookupQualifiedName(TmpRes, Ctx)) continue;
4413 // Any corrections added below will be validated in subsequent
4414 // iterations of the main while() loop over the Consumer's contents.
4415 switch (TmpRes.getResultKind()) {
4416 case LookupResult::Found:
4417 case LookupResult::FoundOverloaded: {
4418 if (SS && SS->isValid()) {
4419 std::string NewQualified = TC.getAsString(getLangOpts());
4420 std::string OldQualified;
4421 llvm::raw_string_ostream OldOStream(OldQualified);
4422 SS->getScopeRep()->print(OldOStream, getPrintingPolicy());
4423 OldOStream << TypoName;
4424 // If correction candidate would be an identical written qualified
4425 // identifer, then the existing CXXScopeSpec probably included a
4426 // typedef that didn't get accounted for properly.
4427 if (OldOStream.str() == NewQualified)
4430 for (LookupResult::iterator TRD = TmpRes.begin(),
4431 TRDEnd = TmpRes.end();
4432 TRD != TRDEnd; ++TRD) {
4433 if (CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4434 NSType ? NSType->getAsCXXRecordDecl() : 0,
4435 TRD.getPair()) == AR_accessible)
4436 TC.addCorrectionDecl(*TRD);
4438 if (TC.isResolved())
4439 Consumer.addCorrection(TC);
4442 case LookupResult::NotFound:
4443 case LookupResult::NotFoundInCurrentInstantiation:
4444 case LookupResult::Ambiguous:
4445 case LookupResult::FoundUnresolvedValue:
4452 QualifiedResults.clear();
4455 // No corrections remain...
4456 if (Consumer.empty())
4457 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4459 TypoResultsMap &BestResults = Consumer.getBestResults();
4460 ED = Consumer.getBestEditDistance(true);
4462 if (!AllowOnlyNNSChanges && ED > 0 && TypoLen / ED < 3) {
4463 // If this was an unqualified lookup and we believe the callback
4464 // object wouldn't have filtered out possible corrections, note
4465 // that no correction was found.
4466 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure,
4467 IsUnqualifiedLookup && !ValidatingCallback);
4470 // If only a single name remains, return that result.
4471 if (BestResults.size() == 1) {
4472 const TypoResultList &CorrectionList = BestResults.begin()->second;
4473 const TypoCorrection &Result = CorrectionList.front();
4474 if (CorrectionList.size() != 1)
4475 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4477 // Don't correct to a keyword that's the same as the typo; the keyword
4478 // wasn't actually in scope.
4479 if (ED == 0 && Result.isKeyword())
4480 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4482 // Record the correction for unqualified lookup.
4483 if (IsUnqualifiedLookup)
4484 UnqualifiedTyposCorrected[Typo] = Result;
4486 TypoCorrection TC = Result;
4487 TC.setCorrectionRange(SS, TypoName);
4488 checkCorrectionVisibility(*this, TC, TypoName.getName());
4491 else if (BestResults.size() > 1
4492 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4493 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4494 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4495 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4496 && CCC.WantObjCSuper && !CCC.WantRemainingKeywords
4497 && BestResults["super"].front().isKeyword()) {
4498 // Prefer 'super' when we're completing in a message-receiver
4501 // Don't correct to a keyword that's the same as the typo; the keyword
4502 // wasn't actually in scope.
4504 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4506 // Record the correction for unqualified lookup.
4507 if (IsUnqualifiedLookup)
4508 UnqualifiedTyposCorrected[Typo] = BestResults["super"].front();
4510 TypoCorrection TC = BestResults["super"].front();
4511 TC.setCorrectionRange(SS, TypoName);
4515 // If this was an unqualified lookup and we believe the callback object did
4516 // not filter out possible corrections, note that no correction was found.
4517 if (IsUnqualifiedLookup && !ValidatingCallback)
4518 (void)UnqualifiedTyposCorrected[Typo];
4520 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4523 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4527 CorrectionDecls.clear();
4529 CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
4531 if (!CorrectionName)
4532 CorrectionName = CDecl->getDeclName();
4535 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4536 if (CorrectionNameSpec) {
4537 std::string tmpBuffer;
4538 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4539 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4540 PrefixOStream << CorrectionName;
4541 return PrefixOStream.str();
4544 return CorrectionName.getAsString();
4547 bool CorrectionCandidateCallback::ValidateCandidate(const TypoCorrection &candidate) {
4548 if (!candidate.isResolved())
4551 if (candidate.isKeyword())
4552 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4553 WantRemainingKeywords || WantObjCSuper;
4555 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
4556 CDeclEnd = candidate.end();
4557 CDecl != CDeclEnd; ++CDecl) {
4558 if (!isa<TypeDecl>(*CDecl))
4562 return WantTypeSpecifiers;
4565 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4566 bool HasExplicitTemplateArgs)
4567 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
4568 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
4569 WantRemainingKeywords = false;
4572 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4573 if (!candidate.getCorrectionDecl())
4574 return candidate.isKeyword();
4576 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
4577 DIEnd = candidate.end();
4578 DI != DIEnd; ++DI) {
4579 FunctionDecl *FD = 0;
4580 NamedDecl *ND = (*DI)->getUnderlyingDecl();
4581 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4582 FD = FTD->getTemplatedDecl();
4583 if (!HasExplicitTemplateArgs && !FD) {
4584 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4585 // If the Decl is neither a function nor a template function,
4586 // determine if it is a pointer or reference to a function. If so,
4587 // check against the number of arguments expected for the pointee.
4588 QualType ValType = cast<ValueDecl>(ND)->getType();
4589 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4590 ValType = ValType->getPointeeType();
4591 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4592 if (FPT->getNumArgs() == NumArgs)
4596 if (FD && FD->getNumParams() >= NumArgs &&
4597 FD->getMinRequiredArguments() <= NumArgs)
4603 void Sema::diagnoseTypo(const TypoCorrection &Correction,
4604 const PartialDiagnostic &TypoDiag,
4605 bool ErrorRecovery) {
4606 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
4610 /// Find which declaration we should import to provide the definition of
4611 /// the given declaration.
4612 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
4613 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4614 return VD->getDefinition();
4615 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4616 return FD->isDefined(FD) ? FD : 0;
4617 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
4618 return TD->getDefinition();
4619 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
4620 return ID->getDefinition();
4621 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
4622 return PD->getDefinition();
4623 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
4624 return getDefinitionToImport(TD->getTemplatedDecl());
4628 /// \brief Diagnose a successfully-corrected typo. Separated from the correction
4629 /// itself to allow external validation of the result, etc.
4631 /// \param Correction The result of performing typo correction.
4632 /// \param TypoDiag The diagnostic to produce. This will have the corrected
4633 /// string added to it (and usually also a fixit).
4634 /// \param PrevNote A note to use when indicating the location of the entity to
4635 /// which we are correcting. Will have the correction string added to it.
4636 /// \param ErrorRecovery If \c true (the default), the caller is going to
4637 /// recover from the typo as if the corrected string had been typed.
4638 /// In this case, \c PDiag must be an error, and we will attach a fixit
4640 void Sema::diagnoseTypo(const TypoCorrection &Correction,
4641 const PartialDiagnostic &TypoDiag,
4642 const PartialDiagnostic &PrevNote,
4643 bool ErrorRecovery) {
4644 std::string CorrectedStr = Correction.getAsString(getLangOpts());
4645 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
4646 FixItHint FixTypo = FixItHint::CreateReplacement(
4647 Correction.getCorrectionRange(), CorrectedStr);
4649 // Maybe we're just missing a module import.
4650 if (Correction.requiresImport()) {
4651 NamedDecl *Decl = Correction.getCorrectionDecl();
4652 assert(Decl && "import required but no declaration to import");
4654 // Suggest importing a module providing the definition of this entity, if
4656 const NamedDecl *Def = getDefinitionToImport(Decl);
4659 Module *Owner = Def->getOwningModule();
4660 assert(Owner && "definition of hidden declaration is not in a module");
4662 Diag(Correction.getCorrectionRange().getBegin(),
4663 diag::err_module_private_declaration)
4664 << Def << Owner->getFullModuleName();
4665 Diag(Def->getLocation(), diag::note_previous_declaration);
4667 // Recover by implicitly importing this module.
4668 if (!isSFINAEContext() && ErrorRecovery)
4669 createImplicitModuleImport(Correction.getCorrectionRange().getBegin(),
4674 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
4675 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
4677 NamedDecl *ChosenDecl =
4678 Correction.isKeyword() ? 0 : Correction.getCorrectionDecl();
4679 if (PrevNote.getDiagID() && ChosenDecl)
4680 Diag(ChosenDecl->getLocation(), PrevNote)
4681 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);