1 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements name lookup for C, C++, Objective-C, and
13 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/Sema.h"
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/DeclSpec.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Sema/TemplateDeduction.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/Basic/Builtins.h"
30 #include "clang/Basic/LangOptions.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/StringMap.h"
35 #include "llvm/Support/ErrorHandling.h"
44 using namespace clang
;
48 class UnqualUsingEntry
{
49 const DeclContext
*Nominated
;
50 const DeclContext
*CommonAncestor
;
53 UnqualUsingEntry(const DeclContext
*Nominated
,
54 const DeclContext
*CommonAncestor
)
55 : Nominated(Nominated
), CommonAncestor(CommonAncestor
) {
58 const DeclContext
*getCommonAncestor() const {
59 return CommonAncestor
;
62 const DeclContext
*getNominatedNamespace() const {
66 // Sort by the pointer value of the common ancestor.
68 bool operator()(const UnqualUsingEntry
&L
, const UnqualUsingEntry
&R
) {
69 return L
.getCommonAncestor() < R
.getCommonAncestor();
72 bool operator()(const UnqualUsingEntry
&E
, const DeclContext
*DC
) {
73 return E
.getCommonAncestor() < DC
;
76 bool operator()(const DeclContext
*DC
, const UnqualUsingEntry
&E
) {
77 return DC
< E
.getCommonAncestor();
82 /// A collection of using directives, as used by C++ unqualified
84 class UnqualUsingDirectiveSet
{
85 typedef llvm::SmallVector
<UnqualUsingEntry
, 8> ListTy
;
88 llvm::SmallPtrSet
<DeclContext
*, 8> visited
;
91 UnqualUsingDirectiveSet() {}
93 void visitScopeChain(Scope
*S
, Scope
*InnermostFileScope
) {
94 // C++ [namespace.udir]p1:
95 // During unqualified name lookup, the names appear as if they
96 // were declared in the nearest enclosing namespace which contains
97 // both the using-directive and the nominated namespace.
98 DeclContext
*InnermostFileDC
99 = static_cast<DeclContext
*>(InnermostFileScope
->getEntity());
100 assert(InnermostFileDC
&& InnermostFileDC
->isFileContext());
102 for (; S
; S
= S
->getParent()) {
103 if (DeclContext
*Ctx
= static_cast<DeclContext
*>(S
->getEntity())) {
104 DeclContext
*EffectiveDC
= (Ctx
->isFileContext() ? Ctx
: InnermostFileDC
);
105 visit(Ctx
, EffectiveDC
);
107 Scope::udir_iterator I
= S
->using_directives_begin(),
108 End
= S
->using_directives_end();
110 for (; I
!= End
; ++I
)
111 visit(*I
, InnermostFileDC
);
116 // Visits a context and collect all of its using directives
117 // recursively. Treats all using directives as if they were
118 // declared in the context.
120 // A given context is only every visited once, so it is important
121 // that contexts be visited from the inside out in order to get
122 // the effective DCs right.
123 void visit(DeclContext
*DC
, DeclContext
*EffectiveDC
) {
124 if (!visited
.insert(DC
))
127 addUsingDirectives(DC
, EffectiveDC
);
130 // Visits a using directive and collects all of its using
131 // directives recursively. Treats all using directives as if they
132 // were declared in the effective DC.
133 void visit(UsingDirectiveDecl
*UD
, DeclContext
*EffectiveDC
) {
134 DeclContext
*NS
= UD
->getNominatedNamespace();
135 if (!visited
.insert(NS
))
138 addUsingDirective(UD
, EffectiveDC
);
139 addUsingDirectives(NS
, EffectiveDC
);
142 // Adds all the using directives in a context (and those nominated
143 // by its using directives, transitively) as if they appeared in
144 // the given effective context.
145 void addUsingDirectives(DeclContext
*DC
, DeclContext
*EffectiveDC
) {
146 llvm::SmallVector
<DeclContext
*,4> queue
;
148 DeclContext::udir_iterator I
, End
;
149 for (llvm::tie(I
, End
) = DC
->getUsingDirectives(); I
!= End
; ++I
) {
150 UsingDirectiveDecl
*UD
= *I
;
151 DeclContext
*NS
= UD
->getNominatedNamespace();
152 if (visited
.insert(NS
)) {
153 addUsingDirective(UD
, EffectiveDC
);
166 // Add a using directive as if it had been declared in the given
167 // context. This helps implement C++ [namespace.udir]p3:
168 // The using-directive is transitive: if a scope contains a
169 // using-directive that nominates a second namespace that itself
170 // contains using-directives, the effect is as if the
171 // using-directives from the second namespace also appeared in
173 void addUsingDirective(UsingDirectiveDecl
*UD
, DeclContext
*EffectiveDC
) {
174 // Find the common ancestor between the effective context and
175 // the nominated namespace.
176 DeclContext
*Common
= UD
->getNominatedNamespace();
177 while (!Common
->Encloses(EffectiveDC
))
178 Common
= Common
->getParent();
179 Common
= Common
->getPrimaryContext();
181 list
.push_back(UnqualUsingEntry(UD
->getNominatedNamespace(), Common
));
185 std::sort(list
.begin(), list
.end(), UnqualUsingEntry::Comparator());
188 typedef ListTy::const_iterator const_iterator
;
190 const_iterator
begin() const { return list
.begin(); }
191 const_iterator
end() const { return list
.end(); }
193 std::pair
<const_iterator
,const_iterator
>
194 getNamespacesFor(DeclContext
*DC
) const {
195 return std::equal_range(begin(), end(), DC
->getPrimaryContext(),
196 UnqualUsingEntry::Comparator());
201 // Retrieve the set of identifier namespaces that correspond to a
202 // specific kind of name lookup.
203 static inline unsigned getIDNS(Sema::LookupNameKind NameKind
,
205 bool Redeclaration
) {
208 case Sema::LookupOrdinaryName
:
209 case Sema::LookupRedeclarationWithLinkage
:
210 IDNS
= Decl::IDNS_Ordinary
;
212 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Member
| Decl::IDNS_Namespace
;
214 IDNS
|= Decl::IDNS_TagFriend
| Decl::IDNS_OrdinaryFriend
;
218 case Sema::LookupOperatorName
:
219 // Operator lookup is its own crazy thing; it is not the same
220 // as (e.g.) looking up an operator name for redeclaration.
221 assert(!Redeclaration
&& "cannot do redeclaration operator lookup");
222 IDNS
= Decl::IDNS_NonMemberOperator
;
225 case Sema::LookupTagName
:
227 IDNS
= Decl::IDNS_Type
;
229 // When looking for a redeclaration of a tag name, we add:
230 // 1) TagFriend to find undeclared friend decls
231 // 2) Namespace because they can't "overload" with tag decls.
232 // 3) Tag because it includes class templates, which can't
233 // "overload" with tag decls.
235 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_TagFriend
| Decl::IDNS_Namespace
;
237 IDNS
= Decl::IDNS_Tag
;
240 case Sema::LookupLabel
:
241 IDNS
= Decl::IDNS_Label
;
244 case Sema::LookupMemberName
:
245 IDNS
= Decl::IDNS_Member
;
247 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Ordinary
;
250 case Sema::LookupNestedNameSpecifierName
:
251 IDNS
= Decl::IDNS_Type
| Decl::IDNS_Namespace
;
254 case Sema::LookupNamespaceName
:
255 IDNS
= Decl::IDNS_Namespace
;
258 case Sema::LookupUsingDeclName
:
259 IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_Tag
260 | Decl::IDNS_Member
| Decl::IDNS_Using
;
263 case Sema::LookupObjCProtocolName
:
264 IDNS
= Decl::IDNS_ObjCProtocol
;
267 case Sema::LookupAnyName
:
268 IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_Tag
| Decl::IDNS_Member
269 | Decl::IDNS_Using
| Decl::IDNS_Namespace
| Decl::IDNS_ObjCProtocol
276 void LookupResult::configure() {
277 IDNS
= getIDNS(LookupKind
, SemaRef
.getLangOptions().CPlusPlus
,
278 isForRedeclaration());
280 // If we're looking for one of the allocation or deallocation
281 // operators, make sure that the implicitly-declared new and delete
282 // operators can be found.
283 if (!isForRedeclaration()) {
284 switch (NameInfo
.getName().getCXXOverloadedOperator()) {
288 case OO_Array_Delete
:
289 SemaRef
.DeclareGlobalNewDelete();
298 void LookupResult::sanity() const {
299 assert(ResultKind
!= NotFound
|| Decls
.size() == 0);
300 assert(ResultKind
!= Found
|| Decls
.size() == 1);
301 assert(ResultKind
!= FoundOverloaded
|| Decls
.size() > 1 ||
302 (Decls
.size() == 1 &&
303 isa
<FunctionTemplateDecl
>((*begin())->getUnderlyingDecl())));
304 assert(ResultKind
!= FoundUnresolvedValue
|| sanityCheckUnresolved());
305 assert(ResultKind
!= Ambiguous
|| Decls
.size() > 1 ||
306 (Decls
.size() == 1 && (Ambiguity
== AmbiguousBaseSubobjects
||
307 Ambiguity
== AmbiguousBaseSubobjectTypes
)));
308 assert((Paths
!= NULL
) == (ResultKind
== Ambiguous
&&
309 (Ambiguity
== AmbiguousBaseSubobjectTypes
||
310 Ambiguity
== AmbiguousBaseSubobjects
)));
313 // Necessary because CXXBasePaths is not complete in Sema.h
314 void LookupResult::deletePaths(CXXBasePaths
*Paths
) {
318 /// Resolves the result kind of this lookup.
319 void LookupResult::resolveKind() {
320 unsigned N
= Decls
.size();
322 // Fast case: no possible ambiguity.
324 assert(ResultKind
== NotFound
|| ResultKind
== NotFoundInCurrentInstantiation
);
328 // If there's a single decl, we need to examine it to decide what
329 // kind of lookup this is.
331 NamedDecl
*D
= (*Decls
.begin())->getUnderlyingDecl();
332 if (isa
<FunctionTemplateDecl
>(D
))
333 ResultKind
= FoundOverloaded
;
334 else if (isa
<UnresolvedUsingValueDecl
>(D
))
335 ResultKind
= FoundUnresolvedValue
;
339 // Don't do any extra resolution if we've already resolved as ambiguous.
340 if (ResultKind
== Ambiguous
) return;
342 llvm::SmallPtrSet
<NamedDecl
*, 16> Unique
;
343 llvm::SmallPtrSet
<QualType
, 16> UniqueTypes
;
345 bool Ambiguous
= false;
346 bool HasTag
= false, HasFunction
= false, HasNonFunction
= false;
347 bool HasFunctionTemplate
= false, HasUnresolved
= false;
349 unsigned UniqueTagIndex
= 0;
353 NamedDecl
*D
= Decls
[I
]->getUnderlyingDecl();
354 D
= cast
<NamedDecl
>(D
->getCanonicalDecl());
356 // Redeclarations of types via typedef can occur both within a scope
357 // and, through using declarations and directives, across scopes. There is
358 // no ambiguity if they all refer to the same type, so unique based on the
360 if (TypeDecl
*TD
= dyn_cast
<TypeDecl
>(D
)) {
361 if (!TD
->getDeclContext()->isRecord()) {
362 QualType T
= SemaRef
.Context
.getTypeDeclType(TD
);
363 if (!UniqueTypes
.insert(SemaRef
.Context
.getCanonicalType(T
))) {
364 // The type is not unique; pull something off the back and continue
366 Decls
[I
] = Decls
[--N
];
372 if (!Unique
.insert(D
)) {
373 // If it's not unique, pull something off the back (and
374 // continue at this index).
375 Decls
[I
] = Decls
[--N
];
379 // Otherwise, do some decl type analysis and then continue.
381 if (isa
<UnresolvedUsingValueDecl
>(D
)) {
382 HasUnresolved
= true;
383 } else if (isa
<TagDecl
>(D
)) {
388 } else if (isa
<FunctionTemplateDecl
>(D
)) {
390 HasFunctionTemplate
= true;
391 } else if (isa
<FunctionDecl
>(D
)) {
396 HasNonFunction
= true;
401 // C++ [basic.scope.hiding]p2:
402 // A class name or enumeration name can be hidden by the name of
403 // an object, function, or enumerator declared in the same
404 // scope. If a class or enumeration name and an object, function,
405 // or enumerator are declared in the same scope (in any order)
406 // with the same name, the class or enumeration name is hidden
407 // wherever the object, function, or enumerator name is visible.
408 // But it's still an error if there are distinct tag types found,
409 // even if they're not visible. (ref?)
410 if (HideTags
&& HasTag
&& !Ambiguous
&&
411 (HasFunction
|| HasNonFunction
|| HasUnresolved
)) {
412 if (Decls
[UniqueTagIndex
]->getDeclContext()->getRedeclContext()->Equals(
413 Decls
[UniqueTagIndex
? 0 : N
-1]->getDeclContext()->getRedeclContext()))
414 Decls
[UniqueTagIndex
] = Decls
[--N
];
421 if (HasNonFunction
&& (HasFunction
|| HasUnresolved
))
425 setAmbiguous(LookupResult::AmbiguousReference
);
426 else if (HasUnresolved
)
427 ResultKind
= LookupResult::FoundUnresolvedValue
;
428 else if (N
> 1 || HasFunctionTemplate
)
429 ResultKind
= LookupResult::FoundOverloaded
;
431 ResultKind
= LookupResult::Found
;
434 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths
&P
) {
435 CXXBasePaths::const_paths_iterator I
, E
;
436 DeclContext::lookup_iterator DI
, DE
;
437 for (I
= P
.begin(), E
= P
.end(); I
!= E
; ++I
)
438 for (llvm::tie(DI
,DE
) = I
->Decls
; DI
!= DE
; ++DI
)
442 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths
&P
) {
443 Paths
= new CXXBasePaths
;
445 addDeclsFromBasePaths(*Paths
);
447 setAmbiguous(AmbiguousBaseSubobjects
);
450 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths
&P
) {
451 Paths
= new CXXBasePaths
;
453 addDeclsFromBasePaths(*Paths
);
455 setAmbiguous(AmbiguousBaseSubobjectTypes
);
458 void LookupResult::print(llvm::raw_ostream
&Out
) {
459 Out
<< Decls
.size() << " result(s)";
460 if (isAmbiguous()) Out
<< ", ambiguous";
461 if (Paths
) Out
<< ", base paths present";
463 for (iterator I
= begin(), E
= end(); I
!= E
; ++I
) {
469 /// \brief Lookup a builtin function, when name lookup would otherwise
471 static bool LookupBuiltin(Sema
&S
, LookupResult
&R
) {
472 Sema::LookupNameKind NameKind
= R
.getLookupKind();
474 // If we didn't find a use of this identifier, and if the identifier
475 // corresponds to a compiler builtin, create the decl object for the builtin
476 // now, injecting it into translation unit scope, and return it.
477 if (NameKind
== Sema::LookupOrdinaryName
||
478 NameKind
== Sema::LookupRedeclarationWithLinkage
) {
479 IdentifierInfo
*II
= R
.getLookupName().getAsIdentifierInfo();
481 // If this is a builtin on this (or all) targets, create the decl.
482 if (unsigned BuiltinID
= II
->getBuiltinID()) {
483 // In C++, we don't have any predefined library functions like
484 // 'malloc'. Instead, we'll just error.
485 if (S
.getLangOptions().CPlusPlus
&&
486 S
.Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
))
489 if (NamedDecl
*D
= S
.LazilyCreateBuiltin((IdentifierInfo
*)II
,
490 BuiltinID
, S
.TUScope
,
491 R
.isForRedeclaration(),
497 if (R
.isForRedeclaration()) {
498 // If we're redeclaring this function anyway, forget that
499 // this was a builtin at all.
500 S
.Context
.BuiltinInfo
.ForgetBuiltin(BuiltinID
, S
.Context
.Idents
);
511 /// \brief Determine whether we can declare a special member function within
512 /// the class at this point.
513 static bool CanDeclareSpecialMemberFunction(ASTContext
&Context
,
514 const CXXRecordDecl
*Class
) {
515 // Don't do it if the class is invalid.
516 if (Class
->isInvalidDecl())
519 // We need to have a definition for the class.
520 if (!Class
->getDefinition() || Class
->isDependentContext())
523 // We can't be in the middle of defining the class.
524 if (const RecordType
*RecordTy
525 = Context
.getTypeDeclType(Class
)->getAs
<RecordType
>())
526 return !RecordTy
->isBeingDefined();
531 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl
*Class
) {
532 if (!CanDeclareSpecialMemberFunction(Context
, Class
))
535 // If the default constructor has not yet been declared, do so now.
536 if (!Class
->hasDeclaredDefaultConstructor())
537 DeclareImplicitDefaultConstructor(Class
);
539 // If the copy constructor has not yet been declared, do so now.
540 if (!Class
->hasDeclaredCopyConstructor())
541 DeclareImplicitCopyConstructor(Class
);
543 // If the copy assignment operator has not yet been declared, do so now.
544 if (!Class
->hasDeclaredCopyAssignment())
545 DeclareImplicitCopyAssignment(Class
);
547 // If the destructor has not yet been declared, do so now.
548 if (!Class
->hasDeclaredDestructor())
549 DeclareImplicitDestructor(Class
);
552 /// \brief Determine whether this is the name of an implicitly-declared
553 /// special member function.
554 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name
) {
555 switch (Name
.getNameKind()) {
556 case DeclarationName::CXXConstructorName
:
557 case DeclarationName::CXXDestructorName
:
560 case DeclarationName::CXXOperatorName
:
561 return Name
.getCXXOverloadedOperator() == OO_Equal
;
570 /// \brief If there are any implicit member functions with the given name
571 /// that need to be declared in the given declaration context, do so.
572 static void DeclareImplicitMemberFunctionsWithName(Sema
&S
,
573 DeclarationName Name
,
574 const DeclContext
*DC
) {
578 switch (Name
.getNameKind()) {
579 case DeclarationName::CXXConstructorName
:
580 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
))
581 if (Record
->getDefinition() &&
582 CanDeclareSpecialMemberFunction(S
.Context
, Record
)) {
583 if (!Record
->hasDeclaredDefaultConstructor())
584 S
.DeclareImplicitDefaultConstructor(
585 const_cast<CXXRecordDecl
*>(Record
));
586 if (!Record
->hasDeclaredCopyConstructor())
587 S
.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl
*>(Record
));
591 case DeclarationName::CXXDestructorName
:
592 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
))
593 if (Record
->getDefinition() && !Record
->hasDeclaredDestructor() &&
594 CanDeclareSpecialMemberFunction(S
.Context
, Record
))
595 S
.DeclareImplicitDestructor(const_cast<CXXRecordDecl
*>(Record
));
598 case DeclarationName::CXXOperatorName
:
599 if (Name
.getCXXOverloadedOperator() != OO_Equal
)
602 if (const CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(DC
))
603 if (Record
->getDefinition() && !Record
->hasDeclaredCopyAssignment() &&
604 CanDeclareSpecialMemberFunction(S
.Context
, Record
))
605 S
.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl
*>(Record
));
613 // Adds all qualifying matches for a name within a decl context to the
614 // given lookup result. Returns true if any matches were found.
615 static bool LookupDirect(Sema
&S
, LookupResult
&R
, const DeclContext
*DC
) {
618 // Lazily declare C++ special member functions.
619 if (S
.getLangOptions().CPlusPlus
)
620 DeclareImplicitMemberFunctionsWithName(S
, R
.getLookupName(), DC
);
622 // Perform lookup into this declaration context.
623 DeclContext::lookup_const_iterator I
, E
;
624 for (llvm::tie(I
, E
) = DC
->lookup(R
.getLookupName()); I
!= E
; ++I
) {
626 if (R
.isAcceptableDecl(D
)) {
632 if (!Found
&& DC
->isTranslationUnit() && LookupBuiltin(S
, R
))
635 if (R
.getLookupName().getNameKind()
636 != DeclarationName::CXXConversionFunctionName
||
637 R
.getLookupName().getCXXNameType()->isDependentType() ||
638 !isa
<CXXRecordDecl
>(DC
))
642 // A specialization of a conversion function template is not found by
643 // name lookup. Instead, any conversion function templates visible in the
644 // context of the use are considered. [...]
645 const CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DC
);
646 if (!Record
->isDefinition())
649 const UnresolvedSetImpl
*Unresolved
= Record
->getConversionFunctions();
650 for (UnresolvedSetImpl::iterator U
= Unresolved
->begin(),
651 UEnd
= Unresolved
->end(); U
!= UEnd
; ++U
) {
652 FunctionTemplateDecl
*ConvTemplate
= dyn_cast
<FunctionTemplateDecl
>(*U
);
656 // When we're performing lookup for the purposes of redeclaration, just
657 // add the conversion function template. When we deduce template
658 // arguments for specializations, we'll end up unifying the return
659 // type of the new declaration with the type of the function template.
660 if (R
.isForRedeclaration()) {
661 R
.addDecl(ConvTemplate
);
667 // [...] For each such operator, if argument deduction succeeds
668 // (14.9.2.3), the resulting specialization is used as if found by
671 // When referencing a conversion function for any purpose other than
672 // a redeclaration (such that we'll be building an expression with the
673 // result), perform template argument deduction and place the
674 // specialization into the result set. We do this to avoid forcing all
675 // callers to perform special deduction for conversion functions.
676 TemplateDeductionInfo
Info(R
.getSema().Context
, R
.getNameLoc());
677 FunctionDecl
*Specialization
= 0;
679 const FunctionProtoType
*ConvProto
680 = ConvTemplate
->getTemplatedDecl()->getType()->getAs
<FunctionProtoType
>();
681 assert(ConvProto
&& "Nonsensical conversion function template type");
683 // Compute the type of the function that we would expect the conversion
684 // function to have, if it were to match the name given.
685 // FIXME: Calling convention!
686 FunctionProtoType::ExtProtoInfo EPI
= ConvProto
->getExtProtoInfo();
687 EPI
.ExtInfo
= EPI
.ExtInfo
.withCallingConv(CC_Default
);
688 EPI
.HasExceptionSpec
= false;
689 EPI
.HasAnyExceptionSpec
= false;
690 EPI
.NumExceptions
= 0;
691 QualType ExpectedType
692 = R
.getSema().Context
.getFunctionType(R
.getLookupName().getCXXNameType(),
695 // Perform template argument deduction against the type that we would
696 // expect the function to have.
697 if (R
.getSema().DeduceTemplateArguments(ConvTemplate
, 0, ExpectedType
,
698 Specialization
, Info
)
699 == Sema::TDK_Success
) {
700 R
.addDecl(Specialization
);
708 // Performs C++ unqualified lookup into the given file context.
710 CppNamespaceLookup(Sema
&S
, LookupResult
&R
, ASTContext
&Context
,
711 DeclContext
*NS
, UnqualUsingDirectiveSet
&UDirs
) {
713 assert(NS
&& NS
->isFileContext() && "CppNamespaceLookup() requires namespace!");
715 // Perform direct name lookup into the LookupCtx.
716 bool Found
= LookupDirect(S
, R
, NS
);
718 // Perform direct name lookup into the namespaces nominated by the
719 // using directives whose common ancestor is this namespace.
720 UnqualUsingDirectiveSet::const_iterator UI
, UEnd
;
721 llvm::tie(UI
, UEnd
) = UDirs
.getNamespacesFor(NS
);
723 for (; UI
!= UEnd
; ++UI
)
724 if (LookupDirect(S
, R
, UI
->getNominatedNamespace()))
732 static bool isNamespaceOrTranslationUnitScope(Scope
*S
) {
733 if (DeclContext
*Ctx
= static_cast<DeclContext
*>(S
->getEntity()))
734 return Ctx
->isFileContext();
738 // Find the next outer declaration context from this scope. This
739 // routine actually returns the semantic outer context, which may
740 // differ from the lexical context (encoded directly in the Scope
741 // stack) when we are parsing a member of a class template. In this
742 // case, the second element of the pair will be true, to indicate that
743 // name lookup should continue searching in this semantic context when
744 // it leaves the current template parameter scope.
745 static std::pair
<DeclContext
*, bool> findOuterContext(Scope
*S
) {
746 DeclContext
*DC
= static_cast<DeclContext
*>(S
->getEntity());
747 DeclContext
*Lexical
= 0;
748 for (Scope
*OuterS
= S
->getParent(); OuterS
;
749 OuterS
= OuterS
->getParent()) {
750 if (OuterS
->getEntity()) {
751 Lexical
= static_cast<DeclContext
*>(OuterS
->getEntity());
756 // C++ [temp.local]p8:
757 // In the definition of a member of a class template that appears
758 // outside of the namespace containing the class template
759 // definition, the name of a template-parameter hides the name of
760 // a member of this namespace.
767 // template<class T> class B {
772 // template<class C> void N::B<C>::f(C) {
773 // C b; // C is the template parameter, not N::C
776 // In this example, the lexical context we return is the
777 // TranslationUnit, while the semantic context is the namespace N.
778 if (!Lexical
|| !DC
|| !S
->getParent() ||
779 !S
->getParent()->isTemplateParamScope())
780 return std::make_pair(Lexical
, false);
782 // Find the outermost template parameter scope.
783 // For the example, this is the scope for the template parameters of
784 // template<class C>.
785 Scope
*OutermostTemplateScope
= S
->getParent();
786 while (OutermostTemplateScope
->getParent() &&
787 OutermostTemplateScope
->getParent()->isTemplateParamScope())
788 OutermostTemplateScope
= OutermostTemplateScope
->getParent();
790 // Find the namespace context in which the original scope occurs. In
791 // the example, this is namespace N.
792 DeclContext
*Semantic
= DC
;
793 while (!Semantic
->isFileContext())
794 Semantic
= Semantic
->getParent();
796 // Find the declaration context just outside of the template
797 // parameter scope. This is the context in which the template is
798 // being lexically declaration (a namespace context). In the
799 // example, this is the global scope.
800 if (Lexical
->isFileContext() && !Lexical
->Equals(Semantic
) &&
801 Lexical
->Encloses(Semantic
))
802 return std::make_pair(Semantic
, true);
804 return std::make_pair(Lexical
, false);
807 bool Sema::CppLookupName(LookupResult
&R
, Scope
*S
) {
808 assert(getLangOptions().CPlusPlus
&& "Can perform only C++ lookup");
810 DeclarationName Name
= R
.getLookupName();
812 // If this is the name of an implicitly-declared special member function,
813 // go through the scope stack to implicitly declare
814 if (isImplicitlyDeclaredMemberFunctionName(Name
)) {
815 for (Scope
*PreS
= S
; PreS
; PreS
= PreS
->getParent())
816 if (DeclContext
*DC
= static_cast<DeclContext
*>(PreS
->getEntity()))
817 DeclareImplicitMemberFunctionsWithName(*this, Name
, DC
);
820 // Implicitly declare member functions with the name we're looking for, if in
821 // fact we are in a scope where it matters.
824 IdentifierResolver::iterator
825 I
= IdResolver
.begin(Name
),
826 IEnd
= IdResolver
.end();
828 // First we lookup local scope.
829 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
830 // ...During unqualified name lookup (3.4.1), the names appear as if
831 // they were declared in the nearest enclosing namespace which contains
832 // both the using-directive and the nominated namespace.
833 // [Note: in this context, "contains" means "contains directly or
837 // namespace A { int i; }
841 // using namespace A;
842 // ++i; // finds local 'i', A::i appears at global scope
846 DeclContext
*OutsideOfTemplateParamDC
= 0;
847 for (; S
&& !isNamespaceOrTranslationUnitScope(S
); S
= S
->getParent()) {
848 DeclContext
*Ctx
= static_cast<DeclContext
*>(S
->getEntity());
850 // Check whether the IdResolver has anything in this scope.
852 for (; I
!= IEnd
&& S
->isDeclScope(*I
); ++I
) {
853 if (R
.isAcceptableDecl(*I
)) {
860 if (S
->isClassScope())
861 if (CXXRecordDecl
*Record
= dyn_cast_or_null
<CXXRecordDecl
>(Ctx
))
862 R
.setNamingClass(Record
);
866 if (!Ctx
&& S
->isTemplateParamScope() && OutsideOfTemplateParamDC
&&
867 S
->getParent() && !S
->getParent()->isTemplateParamScope()) {
868 // We've just searched the last template parameter scope and
869 // found nothing, so look into the the contexts between the
870 // lexical and semantic declaration contexts returned by
871 // findOuterContext(). This implements the name lookup behavior
872 // of C++ [temp.local]p8.
873 Ctx
= OutsideOfTemplateParamDC
;
874 OutsideOfTemplateParamDC
= 0;
878 DeclContext
*OuterCtx
;
879 bool SearchAfterTemplateScope
;
880 llvm::tie(OuterCtx
, SearchAfterTemplateScope
) = findOuterContext(S
);
881 if (SearchAfterTemplateScope
)
882 OutsideOfTemplateParamDC
= OuterCtx
;
884 for (; Ctx
&& !Ctx
->Equals(OuterCtx
); Ctx
= Ctx
->getLookupParent()) {
885 // We do not directly look into transparent contexts, since
886 // those entities will be found in the nearest enclosing
887 // non-transparent context.
888 if (Ctx
->isTransparentContext())
891 // We do not look directly into function or method contexts,
892 // since all of the local variables and parameters of the
893 // function/method are present within the Scope.
894 if (Ctx
->isFunctionOrMethod()) {
895 // If we have an Objective-C instance method, look for ivars
896 // in the corresponding interface.
897 if (ObjCMethodDecl
*Method
= dyn_cast
<ObjCMethodDecl
>(Ctx
)) {
898 if (Method
->isInstanceMethod() && Name
.getAsIdentifierInfo())
899 if (ObjCInterfaceDecl
*Class
= Method
->getClassInterface()) {
900 ObjCInterfaceDecl
*ClassDeclared
;
901 if (ObjCIvarDecl
*Ivar
= Class
->lookupInstanceVariable(
902 Name
.getAsIdentifierInfo(),
904 if (R
.isAcceptableDecl(Ivar
)) {
916 // Perform qualified name lookup into this context.
917 // FIXME: In some cases, we know that every name that could be found by
918 // this qualified name lookup will also be on the identifier chain. For
919 // example, inside a class without any base classes, we never need to
920 // perform qualified lookup because all of the members are on top of the
922 if (LookupQualifiedName(R
, Ctx
, /*InUnqualifiedLookup=*/true))
928 // Stop if we ran out of scopes.
929 // FIXME: This really, really shouldn't be happening.
930 if (!S
) return false;
932 // If we are looking for members, no need to look into global/namespace scope.
933 if (R
.getLookupKind() == LookupMemberName
)
936 // Collect UsingDirectiveDecls in all scopes, and recursively all
937 // nominated namespaces by those using-directives.
939 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
940 // don't build it for each lookup!
942 UnqualUsingDirectiveSet UDirs
;
943 UDirs
.visitScopeChain(Initial
, S
);
946 // Lookup namespace scope, and global scope.
947 // Unqualified name lookup in C++ requires looking into scopes
948 // that aren't strictly lexical, and therefore we walk through the
949 // context as well as walking through the scopes.
951 for (; S
; S
= S
->getParent()) {
952 // Check whether the IdResolver has anything in this scope.
954 for (; I
!= IEnd
&& S
->isDeclScope(*I
); ++I
) {
955 if (R
.isAcceptableDecl(*I
)) {
956 // We found something. Look for anything else in our scope
957 // with this same name and in an acceptable identifier
958 // namespace, so that we can construct an overload set if we
965 if (Found
&& S
->isTemplateParamScope()) {
970 DeclContext
*Ctx
= static_cast<DeclContext
*>(S
->getEntity());
971 if (!Ctx
&& S
->isTemplateParamScope() && OutsideOfTemplateParamDC
&&
972 S
->getParent() && !S
->getParent()->isTemplateParamScope()) {
973 // We've just searched the last template parameter scope and
974 // found nothing, so look into the the contexts between the
975 // lexical and semantic declaration contexts returned by
976 // findOuterContext(). This implements the name lookup behavior
977 // of C++ [temp.local]p8.
978 Ctx
= OutsideOfTemplateParamDC
;
979 OutsideOfTemplateParamDC
= 0;
983 DeclContext
*OuterCtx
;
984 bool SearchAfterTemplateScope
;
985 llvm::tie(OuterCtx
, SearchAfterTemplateScope
) = findOuterContext(S
);
986 if (SearchAfterTemplateScope
)
987 OutsideOfTemplateParamDC
= OuterCtx
;
989 for (; Ctx
&& !Ctx
->Equals(OuterCtx
); Ctx
= Ctx
->getLookupParent()) {
990 // We do not directly look into transparent contexts, since
991 // those entities will be found in the nearest enclosing
992 // non-transparent context.
993 if (Ctx
->isTransparentContext())
996 // If we have a context, and it's not a context stashed in the
997 // template parameter scope for an out-of-line definition, also
998 // look into that context.
999 if (!(Found
&& S
&& S
->isTemplateParamScope())) {
1000 assert(Ctx
->isFileContext() &&
1001 "We should have been looking only at file context here already.");
1003 // Look into context considering using-directives.
1004 if (CppNamespaceLookup(*this, R
, Context
, Ctx
, UDirs
))
1013 if (R
.isForRedeclaration() && !Ctx
->isTransparentContext())
1018 if (R
.isForRedeclaration() && Ctx
&& !Ctx
->isTransparentContext())
1025 /// @brief Perform unqualified name lookup starting from a given
1028 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1029 /// used to find names within the current scope. For example, 'x' in
1033 /// return x; // unqualified name look finds 'x' in the global scope
1037 /// Different lookup criteria can find different names. For example, a
1038 /// particular scope can have both a struct and a function of the same
1039 /// name, and each can be found by certain lookup criteria. For more
1040 /// information about lookup criteria, see the documentation for the
1041 /// class LookupCriteria.
1043 /// @param S The scope from which unqualified name lookup will
1044 /// begin. If the lookup criteria permits, name lookup may also search
1045 /// in the parent scopes.
1047 /// @param Name The name of the entity that we are searching for.
1049 /// @param Loc If provided, the source location where we're performing
1050 /// name lookup. At present, this is only used to produce diagnostics when
1051 /// C library functions (like "malloc") are implicitly declared.
1053 /// @returns The result of name lookup, which includes zero or more
1054 /// declarations and possibly additional information used to diagnose
1056 bool Sema::LookupName(LookupResult
&R
, Scope
*S
, bool AllowBuiltinCreation
) {
1057 DeclarationName Name
= R
.getLookupName();
1058 if (!Name
) return false;
1060 LookupNameKind NameKind
= R
.getLookupKind();
1062 if (!getLangOptions().CPlusPlus
) {
1063 // Unqualified name lookup in C/Objective-C is purely lexical, so
1064 // search in the declarations attached to the name.
1065 if (NameKind
== Sema::LookupRedeclarationWithLinkage
) {
1066 // Find the nearest non-transparent declaration scope.
1067 while (!(S
->getFlags() & Scope::DeclScope
) ||
1069 static_cast<DeclContext
*>(S
->getEntity())
1070 ->isTransparentContext()))
1074 unsigned IDNS
= R
.getIdentifierNamespace();
1076 // Scan up the scope chain looking for a decl that matches this
1077 // identifier that is in the appropriate namespace. This search
1078 // should not take long, as shadowing of names is uncommon, and
1079 // deep shadowing is extremely uncommon.
1080 bool LeftStartingScope
= false;
1082 for (IdentifierResolver::iterator I
= IdResolver
.begin(Name
),
1083 IEnd
= IdResolver
.end();
1085 if ((*I
)->isInIdentifierNamespace(IDNS
)) {
1086 if (NameKind
== LookupRedeclarationWithLinkage
) {
1087 // Determine whether this (or a previous) declaration is
1089 if (!LeftStartingScope
&& !S
->isDeclScope(*I
))
1090 LeftStartingScope
= true;
1092 // If we found something outside of our starting scope that
1093 // does not have linkage, skip it.
1094 if (LeftStartingScope
&& !((*I
)->hasLinkage()))
1100 if ((*I
)->getAttr
<OverloadableAttr
>()) {
1101 // If this declaration has the "overloadable" attribute, we
1102 // might have a set of overloaded functions.
1104 // Figure out what scope the identifier is in.
1105 while (!(S
->getFlags() & Scope::DeclScope
) ||
1106 !S
->isDeclScope(*I
))
1109 // Find the last declaration in this scope (with the same
1110 // name, naturally).
1111 IdentifierResolver::iterator LastI
= I
;
1112 for (++LastI
; LastI
!= IEnd
; ++LastI
) {
1113 if (!S
->isDeclScope(*LastI
))
1124 // Perform C++ unqualified name lookup.
1125 if (CppLookupName(R
, S
))
1129 // If we didn't find a use of this identifier, and if the identifier
1130 // corresponds to a compiler builtin, create the decl object for the builtin
1131 // now, injecting it into translation unit scope, and return it.
1132 if (AllowBuiltinCreation
)
1133 return LookupBuiltin(*this, R
);
1138 /// @brief Perform qualified name lookup in the namespaces nominated by
1139 /// using directives by the given context.
1141 /// C++98 [namespace.qual]p2:
1142 /// Given X::m (where X is a user-declared namespace), or given ::m
1143 /// (where X is the global namespace), let S be the set of all
1144 /// declarations of m in X and in the transitive closure of all
1145 /// namespaces nominated by using-directives in X and its used
1146 /// namespaces, except that using-directives are ignored in any
1147 /// namespace, including X, directly containing one or more
1148 /// declarations of m. No namespace is searched more than once in
1149 /// the lookup of a name. If S is the empty set, the program is
1150 /// ill-formed. Otherwise, if S has exactly one member, or if the
1151 /// context of the reference is a using-declaration
1152 /// (namespace.udecl), S is the required set of declarations of
1153 /// m. Otherwise if the use of m is not one that allows a unique
1154 /// declaration to be chosen from S, the program is ill-formed.
1155 /// C++98 [namespace.qual]p5:
1156 /// During the lookup of a qualified namespace member name, if the
1157 /// lookup finds more than one declaration of the member, and if one
1158 /// declaration introduces a class name or enumeration name and the
1159 /// other declarations either introduce the same object, the same
1160 /// enumerator or a set of functions, the non-type name hides the
1161 /// class or enumeration name if and only if the declarations are
1162 /// from the same namespace; otherwise (the declarations are from
1163 /// different namespaces), the program is ill-formed.
1164 static bool LookupQualifiedNameInUsingDirectives(Sema
&S
, LookupResult
&R
,
1165 DeclContext
*StartDC
) {
1166 assert(StartDC
->isFileContext() && "start context is not a file context");
1168 DeclContext::udir_iterator I
= StartDC
->using_directives_begin();
1169 DeclContext::udir_iterator E
= StartDC
->using_directives_end();
1171 if (I
== E
) return false;
1173 // We have at least added all these contexts to the queue.
1174 llvm::DenseSet
<DeclContext
*> Visited
;
1175 Visited
.insert(StartDC
);
1177 // We have not yet looked into these namespaces, much less added
1178 // their "using-children" to the queue.
1179 llvm::SmallVector
<NamespaceDecl
*, 8> Queue
;
1181 // We have already looked into the initial namespace; seed the queue
1182 // with its using-children.
1183 for (; I
!= E
; ++I
) {
1184 NamespaceDecl
*ND
= (*I
)->getNominatedNamespace()->getOriginalNamespace();
1185 if (Visited
.insert(ND
).second
)
1186 Queue
.push_back(ND
);
1189 // The easiest way to implement the restriction in [namespace.qual]p5
1190 // is to check whether any of the individual results found a tag
1191 // and, if so, to declare an ambiguity if the final result is not
1193 bool FoundTag
= false;
1194 bool FoundNonTag
= false;
1196 LookupResult
LocalR(LookupResult::Temporary
, R
);
1199 while (!Queue
.empty()) {
1200 NamespaceDecl
*ND
= Queue
.back();
1203 // We go through some convolutions here to avoid copying results
1204 // between LookupResults.
1205 bool UseLocal
= !R
.empty();
1206 LookupResult
&DirectR
= UseLocal
? LocalR
: R
;
1207 bool FoundDirect
= LookupDirect(S
, DirectR
, ND
);
1210 // First do any local hiding.
1211 DirectR
.resolveKind();
1213 // If the local result is a tag, remember that.
1214 if (DirectR
.isSingleTagDecl())
1219 // Append the local results to the total results if necessary.
1221 R
.addAllDecls(LocalR
);
1226 // If we find names in this namespace, ignore its using directives.
1232 for (llvm::tie(I
,E
) = ND
->getUsingDirectives(); I
!= E
; ++I
) {
1233 NamespaceDecl
*Nom
= (*I
)->getNominatedNamespace();
1234 if (Visited
.insert(Nom
).second
)
1235 Queue
.push_back(Nom
);
1240 if (FoundTag
&& FoundNonTag
)
1241 R
.setAmbiguousQualifiedTagHiding();
1249 /// \brief Callback that looks for any member of a class with the given name.
1250 static bool LookupAnyMember(const CXXBaseSpecifier
*Specifier
,
1253 RecordDecl
*BaseRecord
= Specifier
->getType()->getAs
<RecordType
>()->getDecl();
1255 DeclarationName N
= DeclarationName::getFromOpaquePtr(Name
);
1256 Path
.Decls
= BaseRecord
->lookup(N
);
1257 return Path
.Decls
.first
!= Path
.Decls
.second
;
1260 /// \brief Determine whether the given set of member declarations contains only
1261 /// static members, nested types, and enumerators.
1262 template<typename InputIterator
>
1263 static bool HasOnlyStaticMembers(InputIterator First
, InputIterator Last
) {
1264 Decl
*D
= (*First
)->getUnderlyingDecl();
1265 if (isa
<VarDecl
>(D
) || isa
<TypeDecl
>(D
) || isa
<EnumConstantDecl
>(D
))
1268 if (isa
<CXXMethodDecl
>(D
)) {
1269 // Determine whether all of the methods are static.
1270 bool AllMethodsAreStatic
= true;
1271 for(; First
!= Last
; ++First
) {
1272 D
= (*First
)->getUnderlyingDecl();
1274 if (!isa
<CXXMethodDecl
>(D
)) {
1275 assert(isa
<TagDecl
>(D
) && "Non-function must be a tag decl");
1279 if (!cast
<CXXMethodDecl
>(D
)->isStatic()) {
1280 AllMethodsAreStatic
= false;
1285 if (AllMethodsAreStatic
)
1292 /// \brief Perform qualified name lookup into a given context.
1294 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1295 /// names when the context of those names is explicit specified, e.g.,
1296 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1298 /// Different lookup criteria can find different names. For example, a
1299 /// particular scope can have both a struct and a function of the same
1300 /// name, and each can be found by certain lookup criteria. For more
1301 /// information about lookup criteria, see the documentation for the
1302 /// class LookupCriteria.
1304 /// \param R captures both the lookup criteria and any lookup results found.
1306 /// \param LookupCtx The context in which qualified name lookup will
1307 /// search. If the lookup criteria permits, name lookup may also search
1308 /// in the parent contexts or (for C++ classes) base classes.
1310 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1311 /// occurs as part of unqualified name lookup.
1313 /// \returns true if lookup succeeded, false if it failed.
1314 bool Sema::LookupQualifiedName(LookupResult
&R
, DeclContext
*LookupCtx
,
1315 bool InUnqualifiedLookup
) {
1316 assert(LookupCtx
&& "Sema::LookupQualifiedName requires a lookup context");
1318 if (!R
.getLookupName())
1321 // Make sure that the declaration context is complete.
1322 assert((!isa
<TagDecl
>(LookupCtx
) ||
1323 LookupCtx
->isDependentContext() ||
1324 cast
<TagDecl
>(LookupCtx
)->isDefinition() ||
1325 Context
.getTypeDeclType(cast
<TagDecl
>(LookupCtx
))->getAs
<TagType
>()
1326 ->isBeingDefined()) &&
1327 "Declaration context must already be complete!");
1329 // Perform qualified name lookup into the LookupCtx.
1330 if (LookupDirect(*this, R
, LookupCtx
)) {
1332 if (isa
<CXXRecordDecl
>(LookupCtx
))
1333 R
.setNamingClass(cast
<CXXRecordDecl
>(LookupCtx
));
1337 // Don't descend into implied contexts for redeclarations.
1338 // C++98 [namespace.qual]p6:
1339 // In a declaration for a namespace member in which the
1340 // declarator-id is a qualified-id, given that the qualified-id
1341 // for the namespace member has the form
1342 // nested-name-specifier unqualified-id
1343 // the unqualified-id shall name a member of the namespace
1344 // designated by the nested-name-specifier.
1345 // See also [class.mfct]p5 and [class.static.data]p2.
1346 if (R
.isForRedeclaration())
1349 // If this is a namespace, look it up in the implied namespaces.
1350 if (LookupCtx
->isFileContext())
1351 return LookupQualifiedNameInUsingDirectives(*this, R
, LookupCtx
);
1353 // If this isn't a C++ class, we aren't allowed to look into base
1354 // classes, we're done.
1355 CXXRecordDecl
*LookupRec
= dyn_cast
<CXXRecordDecl
>(LookupCtx
);
1356 if (!LookupRec
|| !LookupRec
->getDefinition())
1359 // If we're performing qualified name lookup into a dependent class,
1360 // then we are actually looking into a current instantiation. If we have any
1361 // dependent base classes, then we either have to delay lookup until
1362 // template instantiation time (at which point all bases will be available)
1363 // or we have to fail.
1364 if (!InUnqualifiedLookup
&& LookupRec
->isDependentContext() &&
1365 LookupRec
->hasAnyDependentBases()) {
1366 R
.setNotFoundInCurrentInstantiation();
1370 // Perform lookup into our base classes.
1372 Paths
.setOrigin(LookupRec
);
1374 // Look for this member in our base classes
1375 CXXRecordDecl::BaseMatchesCallback
*BaseCallback
= 0;
1376 switch (R
.getLookupKind()) {
1377 case LookupOrdinaryName
:
1378 case LookupMemberName
:
1379 case LookupRedeclarationWithLinkage
:
1380 BaseCallback
= &CXXRecordDecl::FindOrdinaryMember
;
1384 BaseCallback
= &CXXRecordDecl::FindTagMember
;
1388 BaseCallback
= &LookupAnyMember
;
1391 case LookupUsingDeclName
:
1392 // This lookup is for redeclarations only.
1394 case LookupOperatorName
:
1395 case LookupNamespaceName
:
1396 case LookupObjCProtocolName
:
1398 // These lookups will never find a member in a C++ class (or base class).
1401 case LookupNestedNameSpecifierName
:
1402 BaseCallback
= &CXXRecordDecl::FindNestedNameSpecifierMember
;
1406 if (!LookupRec
->lookupInBases(BaseCallback
,
1407 R
.getLookupName().getAsOpaquePtr(), Paths
))
1410 R
.setNamingClass(LookupRec
);
1412 // C++ [class.member.lookup]p2:
1413 // [...] If the resulting set of declarations are not all from
1414 // sub-objects of the same type, or the set has a nonstatic member
1415 // and includes members from distinct sub-objects, there is an
1416 // ambiguity and the program is ill-formed. Otherwise that set is
1417 // the result of the lookup.
1418 QualType SubobjectType
;
1419 int SubobjectNumber
= 0;
1420 AccessSpecifier SubobjectAccess
= AS_none
;
1422 for (CXXBasePaths::paths_iterator Path
= Paths
.begin(), PathEnd
= Paths
.end();
1423 Path
!= PathEnd
; ++Path
) {
1424 const CXXBasePathElement
&PathElement
= Path
->back();
1426 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1427 // across all paths.
1428 SubobjectAccess
= std::min(SubobjectAccess
, Path
->Access
);
1430 // Determine whether we're looking at a distinct sub-object or not.
1431 if (SubobjectType
.isNull()) {
1432 // This is the first subobject we've looked at. Record its type.
1433 SubobjectType
= Context
.getCanonicalType(PathElement
.Base
->getType());
1434 SubobjectNumber
= PathElement
.SubobjectNumber
;
1439 != Context
.getCanonicalType(PathElement
.Base
->getType())) {
1440 // We found members of the given name in two subobjects of
1441 // different types. If the declaration sets aren't the same, this
1442 // this lookup is ambiguous.
1443 if (HasOnlyStaticMembers(Path
->Decls
.first
, Path
->Decls
.second
)) {
1444 CXXBasePaths::paths_iterator FirstPath
= Paths
.begin();
1445 DeclContext::lookup_iterator FirstD
= FirstPath
->Decls
.first
;
1446 DeclContext::lookup_iterator CurrentD
= Path
->Decls
.first
;
1448 while (FirstD
!= FirstPath
->Decls
.second
&&
1449 CurrentD
!= Path
->Decls
.second
) {
1450 if ((*FirstD
)->getUnderlyingDecl()->getCanonicalDecl() !=
1451 (*CurrentD
)->getUnderlyingDecl()->getCanonicalDecl())
1458 if (FirstD
== FirstPath
->Decls
.second
&&
1459 CurrentD
== Path
->Decls
.second
)
1463 R
.setAmbiguousBaseSubobjectTypes(Paths
);
1467 if (SubobjectNumber
!= PathElement
.SubobjectNumber
) {
1468 // We have a different subobject of the same type.
1470 // C++ [class.member.lookup]p5:
1471 // A static member, a nested type or an enumerator defined in
1472 // a base class T can unambiguously be found even if an object
1473 // has more than one base class subobject of type T.
1474 if (HasOnlyStaticMembers(Path
->Decls
.first
, Path
->Decls
.second
))
1477 // We have found a nonstatic member name in multiple, distinct
1478 // subobjects. Name lookup is ambiguous.
1479 R
.setAmbiguousBaseSubobjects(Paths
);
1484 // Lookup in a base class succeeded; return these results.
1486 DeclContext::lookup_iterator I
, E
;
1487 for (llvm::tie(I
,E
) = Paths
.front().Decls
; I
!= E
; ++I
) {
1489 AccessSpecifier AS
= CXXRecordDecl::MergeAccess(SubobjectAccess
,
1497 /// @brief Performs name lookup for a name that was parsed in the
1498 /// source code, and may contain a C++ scope specifier.
1500 /// This routine is a convenience routine meant to be called from
1501 /// contexts that receive a name and an optional C++ scope specifier
1502 /// (e.g., "N::M::x"). It will then perform either qualified or
1503 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1504 /// respectively) on the given name and return those results.
1506 /// @param S The scope from which unqualified name lookup will
1509 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1511 /// @param EnteringContext Indicates whether we are going to enter the
1512 /// context of the scope-specifier SS (if present).
1514 /// @returns True if any decls were found (but possibly ambiguous)
1515 bool Sema::LookupParsedName(LookupResult
&R
, Scope
*S
, CXXScopeSpec
*SS
,
1516 bool AllowBuiltinCreation
, bool EnteringContext
) {
1517 if (SS
&& SS
->isInvalid()) {
1518 // When the scope specifier is invalid, don't even look for
1523 if (SS
&& SS
->isSet()) {
1524 if (DeclContext
*DC
= computeDeclContext(*SS
, EnteringContext
)) {
1525 // We have resolved the scope specifier to a particular declaration
1526 // contex, and will perform name lookup in that context.
1527 if (!DC
->isDependentContext() && RequireCompleteDeclContext(*SS
, DC
))
1530 R
.setContextRange(SS
->getRange());
1532 return LookupQualifiedName(R
, DC
);
1535 // We could not resolve the scope specified to a specific declaration
1536 // context, which means that SS refers to an unknown specialization.
1537 // Name lookup can't find anything in this case.
1541 // Perform unqualified name lookup starting in the given scope.
1542 return LookupName(R
, S
, AllowBuiltinCreation
);
1546 /// @brief Produce a diagnostic describing the ambiguity that resulted
1547 /// from name lookup.
1549 /// @param Result The ambiguous name lookup result.
1551 /// @param Name The name of the entity that name lookup was
1554 /// @param NameLoc The location of the name within the source code.
1556 /// @param LookupRange A source range that provides more
1557 /// source-location information concerning the lookup itself. For
1558 /// example, this range might highlight a nested-name-specifier that
1559 /// precedes the name.
1562 bool Sema::DiagnoseAmbiguousLookup(LookupResult
&Result
) {
1563 assert(Result
.isAmbiguous() && "Lookup result must be ambiguous");
1565 DeclarationName Name
= Result
.getLookupName();
1566 SourceLocation NameLoc
= Result
.getNameLoc();
1567 SourceRange LookupRange
= Result
.getContextRange();
1569 switch (Result
.getAmbiguityKind()) {
1570 case LookupResult::AmbiguousBaseSubobjects
: {
1571 CXXBasePaths
*Paths
= Result
.getBasePaths();
1572 QualType SubobjectType
= Paths
->front().back().Base
->getType();
1573 Diag(NameLoc
, diag::err_ambiguous_member_multiple_subobjects
)
1574 << Name
<< SubobjectType
<< getAmbiguousPathsDisplayString(*Paths
)
1577 DeclContext::lookup_iterator Found
= Paths
->front().Decls
.first
;
1578 while (isa
<CXXMethodDecl
>(*Found
) &&
1579 cast
<CXXMethodDecl
>(*Found
)->isStatic())
1582 Diag((*Found
)->getLocation(), diag::note_ambiguous_member_found
);
1587 case LookupResult::AmbiguousBaseSubobjectTypes
: {
1588 Diag(NameLoc
, diag::err_ambiguous_member_multiple_subobject_types
)
1589 << Name
<< LookupRange
;
1591 CXXBasePaths
*Paths
= Result
.getBasePaths();
1592 std::set
<Decl
*> DeclsPrinted
;
1593 for (CXXBasePaths::paths_iterator Path
= Paths
->begin(),
1594 PathEnd
= Paths
->end();
1595 Path
!= PathEnd
; ++Path
) {
1596 Decl
*D
= *Path
->Decls
.first
;
1597 if (DeclsPrinted
.insert(D
).second
)
1598 Diag(D
->getLocation(), diag::note_ambiguous_member_found
);
1604 case LookupResult::AmbiguousTagHiding
: {
1605 Diag(NameLoc
, diag::err_ambiguous_tag_hiding
) << Name
<< LookupRange
;
1607 llvm::SmallPtrSet
<NamedDecl
*,8> TagDecls
;
1609 LookupResult::iterator DI
, DE
= Result
.end();
1610 for (DI
= Result
.begin(); DI
!= DE
; ++DI
)
1611 if (TagDecl
*TD
= dyn_cast
<TagDecl
>(*DI
)) {
1612 TagDecls
.insert(TD
);
1613 Diag(TD
->getLocation(), diag::note_hidden_tag
);
1616 for (DI
= Result
.begin(); DI
!= DE
; ++DI
)
1617 if (!isa
<TagDecl
>(*DI
))
1618 Diag((*DI
)->getLocation(), diag::note_hiding_object
);
1620 // For recovery purposes, go ahead and implement the hiding.
1621 LookupResult::Filter F
= Result
.makeFilter();
1622 while (F
.hasNext()) {
1623 if (TagDecls
.count(F
.next()))
1631 case LookupResult::AmbiguousReference
: {
1632 Diag(NameLoc
, diag::err_ambiguous_reference
) << Name
<< LookupRange
;
1634 LookupResult::iterator DI
= Result
.begin(), DE
= Result
.end();
1635 for (; DI
!= DE
; ++DI
)
1636 Diag((*DI
)->getLocation(), diag::note_ambiguous_candidate
) << *DI
;
1642 llvm_unreachable("unknown ambiguity kind");
1647 struct AssociatedLookup
{
1648 AssociatedLookup(Sema
&S
,
1649 Sema::AssociatedNamespaceSet
&Namespaces
,
1650 Sema::AssociatedClassSet
&Classes
)
1651 : S(S
), Namespaces(Namespaces
), Classes(Classes
) {
1655 Sema::AssociatedNamespaceSet
&Namespaces
;
1656 Sema::AssociatedClassSet
&Classes
;
1661 addAssociatedClassesAndNamespaces(AssociatedLookup
&Result
, QualType T
);
1663 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet
&Namespaces
,
1665 // Add the associated namespace for this class.
1667 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1668 // be a locally scoped record.
1670 // We skip out of inline namespaces. The innermost non-inline namespace
1671 // contains all names of all its nested inline namespaces anyway, so we can
1672 // replace the entire inline namespace tree with its root.
1673 while (Ctx
->isRecord() || Ctx
->isTransparentContext() ||
1674 Ctx
->isInlineNamespace())
1675 Ctx
= Ctx
->getParent();
1677 if (Ctx
->isFileContext())
1678 Namespaces
.insert(Ctx
->getPrimaryContext());
1681 // \brief Add the associated classes and namespaces for argument-dependent
1682 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1684 addAssociatedClassesAndNamespaces(AssociatedLookup
&Result
,
1685 const TemplateArgument
&Arg
) {
1686 // C++ [basic.lookup.koenig]p2, last bullet:
1688 switch (Arg
.getKind()) {
1689 case TemplateArgument::Null
:
1692 case TemplateArgument::Type
:
1693 // [...] the namespaces and classes associated with the types of the
1694 // template arguments provided for template type parameters (excluding
1695 // template template parameters)
1696 addAssociatedClassesAndNamespaces(Result
, Arg
.getAsType());
1699 case TemplateArgument::Template
:
1700 case TemplateArgument::TemplateExpansion
: {
1701 // [...] the namespaces in which any template template arguments are
1702 // defined; and the classes in which any member templates used as
1703 // template template arguments are defined.
1704 TemplateName Template
= Arg
.getAsTemplateOrTemplatePattern();
1705 if (ClassTemplateDecl
*ClassTemplate
1706 = dyn_cast
<ClassTemplateDecl
>(Template
.getAsTemplateDecl())) {
1707 DeclContext
*Ctx
= ClassTemplate
->getDeclContext();
1708 if (CXXRecordDecl
*EnclosingClass
= dyn_cast
<CXXRecordDecl
>(Ctx
))
1709 Result
.Classes
.insert(EnclosingClass
);
1710 // Add the associated namespace for this class.
1711 CollectEnclosingNamespace(Result
.Namespaces
, Ctx
);
1716 case TemplateArgument::Declaration
:
1717 case TemplateArgument::Integral
:
1718 case TemplateArgument::Expression
:
1719 // [Note: non-type template arguments do not contribute to the set of
1720 // associated namespaces. ]
1723 case TemplateArgument::Pack
:
1724 for (TemplateArgument::pack_iterator P
= Arg
.pack_begin(),
1725 PEnd
= Arg
.pack_end();
1727 addAssociatedClassesAndNamespaces(Result
, *P
);
1732 // \brief Add the associated classes and namespaces for
1733 // argument-dependent lookup with an argument of class type
1734 // (C++ [basic.lookup.koenig]p2).
1736 addAssociatedClassesAndNamespaces(AssociatedLookup
&Result
,
1737 CXXRecordDecl
*Class
) {
1739 // Just silently ignore anything whose name is __va_list_tag.
1740 if (Class
->getDeclName() == Result
.S
.VAListTagName
)
1743 // C++ [basic.lookup.koenig]p2:
1745 // -- If T is a class type (including unions), its associated
1746 // classes are: the class itself; the class of which it is a
1747 // member, if any; and its direct and indirect base
1748 // classes. Its associated namespaces are the namespaces in
1749 // which its associated classes are defined.
1751 // Add the class of which it is a member, if any.
1752 DeclContext
*Ctx
= Class
->getDeclContext();
1753 if (CXXRecordDecl
*EnclosingClass
= dyn_cast
<CXXRecordDecl
>(Ctx
))
1754 Result
.Classes
.insert(EnclosingClass
);
1755 // Add the associated namespace for this class.
1756 CollectEnclosingNamespace(Result
.Namespaces
, Ctx
);
1758 // Add the class itself. If we've already seen this class, we don't
1759 // need to visit base classes.
1760 if (!Result
.Classes
.insert(Class
))
1763 // -- If T is a template-id, its associated namespaces and classes are
1764 // the namespace in which the template is defined; for member
1765 // templates, the member template's class; the namespaces and classes
1766 // associated with the types of the template arguments provided for
1767 // template type parameters (excluding template template parameters); the
1768 // namespaces in which any template template arguments are defined; and
1769 // the classes in which any member templates used as template template
1770 // arguments are defined. [Note: non-type template arguments do not
1771 // contribute to the set of associated namespaces. ]
1772 if (ClassTemplateSpecializationDecl
*Spec
1773 = dyn_cast
<ClassTemplateSpecializationDecl
>(Class
)) {
1774 DeclContext
*Ctx
= Spec
->getSpecializedTemplate()->getDeclContext();
1775 if (CXXRecordDecl
*EnclosingClass
= dyn_cast
<CXXRecordDecl
>(Ctx
))
1776 Result
.Classes
.insert(EnclosingClass
);
1777 // Add the associated namespace for this class.
1778 CollectEnclosingNamespace(Result
.Namespaces
, Ctx
);
1780 const TemplateArgumentList
&TemplateArgs
= Spec
->getTemplateArgs();
1781 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
1782 addAssociatedClassesAndNamespaces(Result
, TemplateArgs
[I
]);
1785 // Only recurse into base classes for complete types.
1786 if (!Class
->hasDefinition()) {
1787 // FIXME: we might need to instantiate templates here
1791 // Add direct and indirect base classes along with their associated
1793 llvm::SmallVector
<CXXRecordDecl
*, 32> Bases
;
1794 Bases
.push_back(Class
);
1795 while (!Bases
.empty()) {
1796 // Pop this class off the stack.
1797 Class
= Bases
.back();
1800 // Visit the base classes.
1801 for (CXXRecordDecl::base_class_iterator Base
= Class
->bases_begin(),
1802 BaseEnd
= Class
->bases_end();
1803 Base
!= BaseEnd
; ++Base
) {
1804 const RecordType
*BaseType
= Base
->getType()->getAs
<RecordType
>();
1805 // In dependent contexts, we do ADL twice, and the first time around,
1806 // the base type might be a dependent TemplateSpecializationType, or a
1807 // TemplateTypeParmType. If that happens, simply ignore it.
1808 // FIXME: If we want to support export, we probably need to add the
1809 // namespace of the template in a TemplateSpecializationType, or even
1810 // the classes and namespaces of known non-dependent arguments.
1813 CXXRecordDecl
*BaseDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
1814 if (Result
.Classes
.insert(BaseDecl
)) {
1815 // Find the associated namespace for this base class.
1816 DeclContext
*BaseCtx
= BaseDecl
->getDeclContext();
1817 CollectEnclosingNamespace(Result
.Namespaces
, BaseCtx
);
1819 // Make sure we visit the bases of this base class.
1820 if (BaseDecl
->bases_begin() != BaseDecl
->bases_end())
1821 Bases
.push_back(BaseDecl
);
1827 // \brief Add the associated classes and namespaces for
1828 // argument-dependent lookup with an argument of type T
1829 // (C++ [basic.lookup.koenig]p2).
1831 addAssociatedClassesAndNamespaces(AssociatedLookup
&Result
, QualType Ty
) {
1832 // C++ [basic.lookup.koenig]p2:
1834 // For each argument type T in the function call, there is a set
1835 // of zero or more associated namespaces and a set of zero or more
1836 // associated classes to be considered. The sets of namespaces and
1837 // classes is determined entirely by the types of the function
1838 // arguments (and the namespace of any template template
1839 // argument). Typedef names and using-declarations used to specify
1840 // the types do not contribute to this set. The sets of namespaces
1841 // and classes are determined in the following way:
1843 llvm::SmallVector
<const Type
*, 16> Queue
;
1844 const Type
*T
= Ty
->getCanonicalTypeInternal().getTypePtr();
1847 switch (T
->getTypeClass()) {
1849 #define TYPE(Class, Base)
1850 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1851 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1852 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1853 #define ABSTRACT_TYPE(Class, Base)
1854 #include "clang/AST/TypeNodes.def"
1855 // T is canonical. We can also ignore dependent types because
1856 // we don't need to do ADL at the definition point, but if we
1857 // wanted to implement template export (or if we find some other
1858 // use for associated classes and namespaces...) this would be
1862 // -- If T is a pointer to U or an array of U, its associated
1863 // namespaces and classes are those associated with U.
1865 T
= cast
<PointerType
>(T
)->getPointeeType().getTypePtr();
1867 case Type::ConstantArray
:
1868 case Type::IncompleteArray
:
1869 case Type::VariableArray
:
1870 T
= cast
<ArrayType
>(T
)->getElementType().getTypePtr();
1873 // -- If T is a fundamental type, its associated sets of
1874 // namespaces and classes are both empty.
1878 // -- If T is a class type (including unions), its associated
1879 // classes are: the class itself; the class of which it is a
1880 // member, if any; and its direct and indirect base
1881 // classes. Its associated namespaces are the namespaces in
1882 // which its associated classes are defined.
1883 case Type::Record
: {
1884 CXXRecordDecl
*Class
1885 = cast
<CXXRecordDecl
>(cast
<RecordType
>(T
)->getDecl());
1886 addAssociatedClassesAndNamespaces(Result
, Class
);
1890 // -- If T is an enumeration type, its associated namespace is
1891 // the namespace in which it is defined. If it is class
1892 // member, its associated class is the member's class; else
1893 // it has no associated class.
1895 EnumDecl
*Enum
= cast
<EnumType
>(T
)->getDecl();
1897 DeclContext
*Ctx
= Enum
->getDeclContext();
1898 if (CXXRecordDecl
*EnclosingClass
= dyn_cast
<CXXRecordDecl
>(Ctx
))
1899 Result
.Classes
.insert(EnclosingClass
);
1901 // Add the associated namespace for this class.
1902 CollectEnclosingNamespace(Result
.Namespaces
, Ctx
);
1907 // -- If T is a function type, its associated namespaces and
1908 // classes are those associated with the function parameter
1909 // types and those associated with the return type.
1910 case Type::FunctionProto
: {
1911 const FunctionProtoType
*Proto
= cast
<FunctionProtoType
>(T
);
1912 for (FunctionProtoType::arg_type_iterator Arg
= Proto
->arg_type_begin(),
1913 ArgEnd
= Proto
->arg_type_end();
1914 Arg
!= ArgEnd
; ++Arg
)
1915 Queue
.push_back(Arg
->getTypePtr());
1918 case Type::FunctionNoProto
: {
1919 const FunctionType
*FnType
= cast
<FunctionType
>(T
);
1920 T
= FnType
->getResultType().getTypePtr();
1924 // -- If T is a pointer to a member function of a class X, its
1925 // associated namespaces and classes are those associated
1926 // with the function parameter types and return type,
1927 // together with those associated with X.
1929 // -- If T is a pointer to a data member of class X, its
1930 // associated namespaces and classes are those associated
1931 // with the member type together with those associated with
1933 case Type::MemberPointer
: {
1934 const MemberPointerType
*MemberPtr
= cast
<MemberPointerType
>(T
);
1936 // Queue up the class type into which this points.
1937 Queue
.push_back(MemberPtr
->getClass());
1939 // And directly continue with the pointee type.
1940 T
= MemberPtr
->getPointeeType().getTypePtr();
1944 // As an extension, treat this like a normal pointer.
1945 case Type::BlockPointer
:
1946 T
= cast
<BlockPointerType
>(T
)->getPointeeType().getTypePtr();
1949 // References aren't covered by the standard, but that's such an
1950 // obvious defect that we cover them anyway.
1951 case Type::LValueReference
:
1952 case Type::RValueReference
:
1953 T
= cast
<ReferenceType
>(T
)->getPointeeType().getTypePtr();
1956 // These are fundamental types.
1958 case Type::ExtVector
:
1962 // These are ignored by ADL.
1963 case Type::ObjCObject
:
1964 case Type::ObjCInterface
:
1965 case Type::ObjCObjectPointer
:
1969 if (Queue
.empty()) break;
1975 /// \brief Find the associated classes and namespaces for
1976 /// argument-dependent lookup for a call with the given set of
1979 /// This routine computes the sets of associated classes and associated
1980 /// namespaces searched by argument-dependent lookup
1981 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1983 Sema::FindAssociatedClassesAndNamespaces(Expr
**Args
, unsigned NumArgs
,
1984 AssociatedNamespaceSet
&AssociatedNamespaces
,
1985 AssociatedClassSet
&AssociatedClasses
) {
1986 AssociatedNamespaces
.clear();
1987 AssociatedClasses
.clear();
1989 AssociatedLookup
Result(*this, AssociatedNamespaces
, AssociatedClasses
);
1991 // C++ [basic.lookup.koenig]p2:
1992 // For each argument type T in the function call, there is a set
1993 // of zero or more associated namespaces and a set of zero or more
1994 // associated classes to be considered. The sets of namespaces and
1995 // classes is determined entirely by the types of the function
1996 // arguments (and the namespace of any template template
1998 for (unsigned ArgIdx
= 0; ArgIdx
!= NumArgs
; ++ArgIdx
) {
1999 Expr
*Arg
= Args
[ArgIdx
];
2001 if (Arg
->getType() != Context
.OverloadTy
) {
2002 addAssociatedClassesAndNamespaces(Result
, Arg
->getType());
2006 // [...] In addition, if the argument is the name or address of a
2007 // set of overloaded functions and/or function templates, its
2008 // associated classes and namespaces are the union of those
2009 // associated with each of the members of the set: the namespace
2010 // in which the function or function template is defined and the
2011 // classes and namespaces associated with its (non-dependent)
2012 // parameter types and return type.
2013 Arg
= Arg
->IgnoreParens();
2014 if (UnaryOperator
*unaryOp
= dyn_cast
<UnaryOperator
>(Arg
))
2015 if (unaryOp
->getOpcode() == UO_AddrOf
)
2016 Arg
= unaryOp
->getSubExpr();
2018 UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(Arg
);
2021 for (UnresolvedSetIterator I
= ULE
->decls_begin(), E
= ULE
->decls_end();
2023 // Look through any using declarations to find the underlying function.
2024 NamedDecl
*Fn
= (*I
)->getUnderlyingDecl();
2026 FunctionDecl
*FDecl
= dyn_cast
<FunctionDecl
>(Fn
);
2028 FDecl
= cast
<FunctionTemplateDecl
>(Fn
)->getTemplatedDecl();
2030 // Add the classes and namespaces associated with the parameter
2031 // types and return type of this function.
2032 addAssociatedClassesAndNamespaces(Result
, FDecl
->getType());
2037 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2038 /// an acceptable non-member overloaded operator for a call whose
2039 /// arguments have types T1 (and, if non-empty, T2). This routine
2040 /// implements the check in C++ [over.match.oper]p3b2 concerning
2041 /// enumeration types.
2043 IsAcceptableNonMemberOperatorCandidate(FunctionDecl
*Fn
,
2044 QualType T1
, QualType T2
,
2045 ASTContext
&Context
) {
2046 if (T1
->isDependentType() || (!T2
.isNull() && T2
->isDependentType()))
2049 if (T1
->isRecordType() || (!T2
.isNull() && T2
->isRecordType()))
2052 const FunctionProtoType
*Proto
= Fn
->getType()->getAs
<FunctionProtoType
>();
2053 if (Proto
->getNumArgs() < 1)
2056 if (T1
->isEnumeralType()) {
2057 QualType ArgType
= Proto
->getArgType(0).getNonReferenceType();
2058 if (Context
.hasSameUnqualifiedType(T1
, ArgType
))
2062 if (Proto
->getNumArgs() < 2)
2065 if (!T2
.isNull() && T2
->isEnumeralType()) {
2066 QualType ArgType
= Proto
->getArgType(1).getNonReferenceType();
2067 if (Context
.hasSameUnqualifiedType(T2
, ArgType
))
2074 NamedDecl
*Sema::LookupSingleName(Scope
*S
, DeclarationName Name
,
2076 LookupNameKind NameKind
,
2077 RedeclarationKind Redecl
) {
2078 LookupResult
R(*this, Name
, Loc
, NameKind
, Redecl
);
2080 return R
.getAsSingle
<NamedDecl
>();
2083 /// \brief Find the protocol with the given name, if any.
2084 ObjCProtocolDecl
*Sema::LookupProtocol(IdentifierInfo
*II
,
2085 SourceLocation IdLoc
) {
2086 Decl
*D
= LookupSingleName(TUScope
, II
, IdLoc
,
2087 LookupObjCProtocolName
);
2088 return cast_or_null
<ObjCProtocolDecl
>(D
);
2091 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op
, Scope
*S
,
2092 QualType T1
, QualType T2
,
2093 UnresolvedSetImpl
&Functions
) {
2094 // C++ [over.match.oper]p3:
2095 // -- The set of non-member candidates is the result of the
2096 // unqualified lookup of operator@ in the context of the
2097 // expression according to the usual rules for name lookup in
2098 // unqualified function calls (3.4.2) except that all member
2099 // functions are ignored. However, if no operand has a class
2100 // type, only those non-member functions in the lookup set
2101 // that have a first parameter of type T1 or "reference to
2102 // (possibly cv-qualified) T1", when T1 is an enumeration
2103 // type, or (if there is a right operand) a second parameter
2104 // of type T2 or "reference to (possibly cv-qualified) T2",
2105 // when T2 is an enumeration type, are candidate functions.
2106 DeclarationName OpName
= Context
.DeclarationNames
.getCXXOperatorName(Op
);
2107 LookupResult
Operators(*this, OpName
, SourceLocation(), LookupOperatorName
);
2108 LookupName(Operators
, S
);
2110 assert(!Operators
.isAmbiguous() && "Operator lookup cannot be ambiguous");
2112 if (Operators
.empty())
2115 for (LookupResult::iterator Op
= Operators
.begin(), OpEnd
= Operators
.end();
2116 Op
!= OpEnd
; ++Op
) {
2117 NamedDecl
*Found
= (*Op
)->getUnderlyingDecl();
2118 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(Found
)) {
2119 if (IsAcceptableNonMemberOperatorCandidate(FD
, T1
, T2
, Context
))
2120 Functions
.addDecl(*Op
, Op
.getAccess()); // FIXME: canonical FD
2121 } else if (FunctionTemplateDecl
*FunTmpl
2122 = dyn_cast
<FunctionTemplateDecl
>(Found
)) {
2123 // FIXME: friend operators?
2124 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2126 if (!FunTmpl
->getDeclContext()->isRecord())
2127 Functions
.addDecl(*Op
, Op
.getAccess());
2132 /// \brief Look up the constructors for the given class.
2133 DeclContext::lookup_result
Sema::LookupConstructors(CXXRecordDecl
*Class
) {
2134 // If the copy constructor has not yet been declared, do so now.
2135 if (CanDeclareSpecialMemberFunction(Context
, Class
)) {
2136 if (!Class
->hasDeclaredDefaultConstructor())
2137 DeclareImplicitDefaultConstructor(Class
);
2138 if (!Class
->hasDeclaredCopyConstructor())
2139 DeclareImplicitCopyConstructor(Class
);
2142 CanQualType T
= Context
.getCanonicalType(Context
.getTypeDeclType(Class
));
2143 DeclarationName Name
= Context
.DeclarationNames
.getCXXConstructorName(T
);
2144 return Class
->lookup(Name
);
2147 /// \brief Look for the destructor of the given class.
2149 /// During semantic analysis, this routine should be used in lieu of
2150 /// CXXRecordDecl::getDestructor().
2152 /// \returns The destructor for this class.
2153 CXXDestructorDecl
*Sema::LookupDestructor(CXXRecordDecl
*Class
) {
2154 // If the destructor has not yet been declared, do so now.
2155 if (CanDeclareSpecialMemberFunction(Context
, Class
) &&
2156 !Class
->hasDeclaredDestructor())
2157 DeclareImplicitDestructor(Class
);
2159 return Class
->getDestructor();
2162 void ADLResult::insert(NamedDecl
*New
) {
2163 NamedDecl
*&Old
= Decls
[cast
<NamedDecl
>(New
->getCanonicalDecl())];
2165 // If we haven't yet seen a decl for this key, or the last decl
2166 // was exactly this one, we're done.
2167 if (Old
== 0 || Old
== New
) {
2172 // Otherwise, decide which is a more recent redeclaration.
2173 FunctionDecl
*OldFD
, *NewFD
;
2174 if (isa
<FunctionTemplateDecl
>(New
)) {
2175 OldFD
= cast
<FunctionTemplateDecl
>(Old
)->getTemplatedDecl();
2176 NewFD
= cast
<FunctionTemplateDecl
>(New
)->getTemplatedDecl();
2178 OldFD
= cast
<FunctionDecl
>(Old
);
2179 NewFD
= cast
<FunctionDecl
>(New
);
2182 FunctionDecl
*Cursor
= NewFD
;
2184 Cursor
= Cursor
->getPreviousDeclaration();
2186 // If we got to the end without finding OldFD, OldFD is the newer
2187 // declaration; leave things as they are.
2188 if (!Cursor
) return;
2190 // If we do find OldFD, then NewFD is newer.
2191 if (Cursor
== OldFD
) break;
2193 // Otherwise, keep looking.
2199 void Sema::ArgumentDependentLookup(DeclarationName Name
, bool Operator
,
2200 Expr
**Args
, unsigned NumArgs
,
2201 ADLResult
&Result
) {
2202 // Find all of the associated namespaces and classes based on the
2203 // arguments we have.
2204 AssociatedNamespaceSet AssociatedNamespaces
;
2205 AssociatedClassSet AssociatedClasses
;
2206 FindAssociatedClassesAndNamespaces(Args
, NumArgs
,
2207 AssociatedNamespaces
,
2212 T1
= Args
[0]->getType();
2214 T2
= Args
[1]->getType();
2217 // C++ [basic.lookup.argdep]p3:
2218 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2219 // and let Y be the lookup set produced by argument dependent
2220 // lookup (defined as follows). If X contains [...] then Y is
2221 // empty. Otherwise Y is the set of declarations found in the
2222 // namespaces associated with the argument types as described
2223 // below. The set of declarations found by the lookup of the name
2224 // is the union of X and Y.
2226 // Here, we compute Y and add its members to the overloaded
2228 for (AssociatedNamespaceSet::iterator NS
= AssociatedNamespaces
.begin(),
2229 NSEnd
= AssociatedNamespaces
.end();
2230 NS
!= NSEnd
; ++NS
) {
2231 // When considering an associated namespace, the lookup is the
2232 // same as the lookup performed when the associated namespace is
2233 // used as a qualifier (3.4.3.2) except that:
2235 // -- Any using-directives in the associated namespace are
2238 // -- Any namespace-scope friend functions declared in
2239 // associated classes are visible within their respective
2240 // namespaces even if they are not visible during an ordinary
2242 DeclContext::lookup_iterator I
, E
;
2243 for (llvm::tie(I
, E
) = (*NS
)->lookup(Name
); I
!= E
; ++I
) {
2245 // If the only declaration here is an ordinary friend, consider
2246 // it only if it was declared in an associated classes.
2247 if (D
->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend
) {
2248 DeclContext
*LexDC
= D
->getLexicalDeclContext();
2249 if (!AssociatedClasses
.count(cast
<CXXRecordDecl
>(LexDC
)))
2253 if (isa
<UsingShadowDecl
>(D
))
2254 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
2256 if (isa
<FunctionDecl
>(D
)) {
2258 !IsAcceptableNonMemberOperatorCandidate(cast
<FunctionDecl
>(D
),
2261 } else if (!isa
<FunctionTemplateDecl
>(D
))
2269 //----------------------------------------------------------------------------
2270 // Search for all visible declarations.
2271 //----------------------------------------------------------------------------
2272 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2276 class ShadowContextRAII
;
2278 class VisibleDeclsRecord
{
2280 /// \brief An entry in the shadow map, which is optimized to store a
2281 /// single declaration (the common case) but can also store a list
2282 /// of declarations.
2283 class ShadowMapEntry
{
2284 typedef llvm::SmallVector
<NamedDecl
*, 4> DeclVector
;
2286 /// \brief Contains either the solitary NamedDecl * or a vector
2287 /// of declarations.
2288 llvm::PointerUnion
<NamedDecl
*, DeclVector
*> DeclOrVector
;
2291 ShadowMapEntry() : DeclOrVector() { }
2293 void Add(NamedDecl
*ND
);
2297 typedef NamedDecl
**iterator
;
2303 /// \brief A mapping from declaration names to the declarations that have
2304 /// this name within a particular scope.
2305 typedef llvm::DenseMap
<DeclarationName
, ShadowMapEntry
> ShadowMap
;
2307 /// \brief A list of shadow maps, which is used to model name hiding.
2308 std::list
<ShadowMap
> ShadowMaps
;
2310 /// \brief The declaration contexts we have already visited.
2311 llvm::SmallPtrSet
<DeclContext
*, 8> VisitedContexts
;
2313 friend class ShadowContextRAII
;
2316 /// \brief Determine whether we have already visited this context
2317 /// (and, if not, note that we are going to visit that context now).
2318 bool visitedContext(DeclContext
*Ctx
) {
2319 return !VisitedContexts
.insert(Ctx
);
2322 bool alreadyVisitedContext(DeclContext
*Ctx
) {
2323 return VisitedContexts
.count(Ctx
);
2326 /// \brief Determine whether the given declaration is hidden in the
2329 /// \returns the declaration that hides the given declaration, or
2330 /// NULL if no such declaration exists.
2331 NamedDecl
*checkHidden(NamedDecl
*ND
);
2333 /// \brief Add a declaration to the current shadow map.
2334 void add(NamedDecl
*ND
) { ShadowMaps
.back()[ND
->getDeclName()].Add(ND
); }
2337 /// \brief RAII object that records when we've entered a shadow context.
2338 class ShadowContextRAII
{
2339 VisibleDeclsRecord
&Visible
;
2341 typedef VisibleDeclsRecord::ShadowMap ShadowMap
;
2344 ShadowContextRAII(VisibleDeclsRecord
&Visible
) : Visible(Visible
) {
2345 Visible
.ShadowMaps
.push_back(ShadowMap());
2348 ~ShadowContextRAII() {
2349 for (ShadowMap::iterator E
= Visible
.ShadowMaps
.back().begin(),
2350 EEnd
= Visible
.ShadowMaps
.back().end();
2353 E
->second
.Destroy();
2355 Visible
.ShadowMaps
.pop_back();
2359 } // end anonymous namespace
2361 void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl
*ND
) {
2362 if (DeclOrVector
.isNull()) {
2363 // 0 - > 1 elements: just set the single element information.
2368 if (NamedDecl
*PrevND
= DeclOrVector
.dyn_cast
<NamedDecl
*>()) {
2369 // 1 -> 2 elements: create the vector of results and push in the
2370 // existing declaration.
2371 DeclVector
*Vec
= new DeclVector
;
2372 Vec
->push_back(PrevND
);
2376 // Add the new element to the end of the vector.
2377 DeclOrVector
.get
<DeclVector
*>()->push_back(ND
);
2380 void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2381 if (DeclVector
*Vec
= DeclOrVector
.dyn_cast
<DeclVector
*>()) {
2383 DeclOrVector
= ((NamedDecl
*)0);
2387 VisibleDeclsRecord::ShadowMapEntry::iterator
2388 VisibleDeclsRecord::ShadowMapEntry::begin() {
2389 if (DeclOrVector
.isNull())
2392 if (DeclOrVector
.dyn_cast
<NamedDecl
*>())
2393 return &reinterpret_cast<NamedDecl
*&>(DeclOrVector
);
2395 return DeclOrVector
.get
<DeclVector
*>()->begin();
2398 VisibleDeclsRecord::ShadowMapEntry::iterator
2399 VisibleDeclsRecord::ShadowMapEntry::end() {
2400 if (DeclOrVector
.isNull())
2403 if (DeclOrVector
.dyn_cast
<NamedDecl
*>())
2404 return &reinterpret_cast<NamedDecl
*&>(DeclOrVector
) + 1;
2406 return DeclOrVector
.get
<DeclVector
*>()->end();
2409 NamedDecl
*VisibleDeclsRecord::checkHidden(NamedDecl
*ND
) {
2410 // Look through using declarations.
2411 ND
= ND
->getUnderlyingDecl();
2413 unsigned IDNS
= ND
->getIdentifierNamespace();
2414 std::list
<ShadowMap
>::reverse_iterator SM
= ShadowMaps
.rbegin();
2415 for (std::list
<ShadowMap
>::reverse_iterator SMEnd
= ShadowMaps
.rend();
2416 SM
!= SMEnd
; ++SM
) {
2417 ShadowMap::iterator Pos
= SM
->find(ND
->getDeclName());
2418 if (Pos
== SM
->end())
2421 for (ShadowMapEntry::iterator I
= Pos
->second
.begin(),
2422 IEnd
= Pos
->second
.end();
2424 // A tag declaration does not hide a non-tag declaration.
2425 if ((*I
)->hasTagIdentifierNamespace() &&
2426 (IDNS
& (Decl::IDNS_Member
| Decl::IDNS_Ordinary
|
2427 Decl::IDNS_ObjCProtocol
)))
2430 // Protocols are in distinct namespaces from everything else.
2431 if ((((*I
)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol
)
2432 || (IDNS
& Decl::IDNS_ObjCProtocol
)) &&
2433 (*I
)->getIdentifierNamespace() != IDNS
)
2436 // Functions and function templates in the same scope overload
2437 // rather than hide. FIXME: Look for hiding based on function
2439 if ((*I
)->isFunctionOrFunctionTemplate() &&
2440 ND
->isFunctionOrFunctionTemplate() &&
2441 SM
== ShadowMaps
.rbegin())
2444 // We've found a declaration that hides this one.
2452 static void LookupVisibleDecls(DeclContext
*Ctx
, LookupResult
&Result
,
2453 bool QualifiedNameLookup
,
2455 VisibleDeclConsumer
&Consumer
,
2456 VisibleDeclsRecord
&Visited
) {
2460 // Make sure we don't visit the same context twice.
2461 if (Visited
.visitedContext(Ctx
->getPrimaryContext()))
2464 if (CXXRecordDecl
*Class
= dyn_cast
<CXXRecordDecl
>(Ctx
))
2465 Result
.getSema().ForceDeclarationOfImplicitMembers(Class
);
2467 // Enumerate all of the results in this context.
2468 for (DeclContext
*CurCtx
= Ctx
->getPrimaryContext(); CurCtx
;
2469 CurCtx
= CurCtx
->getNextContext()) {
2470 for (DeclContext::decl_iterator D
= CurCtx
->decls_begin(),
2471 DEnd
= CurCtx
->decls_end();
2473 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(*D
)) {
2474 if (Result
.isAcceptableDecl(ND
)) {
2475 Consumer
.FoundDecl(ND
, Visited
.checkHidden(ND
), InBaseClass
);
2478 } else if (ObjCForwardProtocolDecl
*ForwardProto
2479 = dyn_cast
<ObjCForwardProtocolDecl
>(*D
)) {
2480 for (ObjCForwardProtocolDecl::protocol_iterator
2481 P
= ForwardProto
->protocol_begin(),
2482 PEnd
= ForwardProto
->protocol_end();
2485 if (Result
.isAcceptableDecl(*P
)) {
2486 Consumer
.FoundDecl(*P
, Visited
.checkHidden(*P
), InBaseClass
);
2490 } else if (ObjCClassDecl
*Class
= dyn_cast
<ObjCClassDecl
>(*D
)) {
2491 for (ObjCClassDecl::iterator I
= Class
->begin(), IEnd
= Class
->end();
2493 ObjCInterfaceDecl
*IFace
= I
->getInterface();
2494 if (Result
.isAcceptableDecl(IFace
)) {
2495 Consumer
.FoundDecl(IFace
, Visited
.checkHidden(IFace
), InBaseClass
);
2501 // Visit transparent contexts and inline namespaces inside this context.
2502 if (DeclContext
*InnerCtx
= dyn_cast
<DeclContext
>(*D
)) {
2503 if (InnerCtx
->isTransparentContext() || InnerCtx
->isInlineNamespace())
2504 LookupVisibleDecls(InnerCtx
, Result
, QualifiedNameLookup
, InBaseClass
,
2510 // Traverse using directives for qualified name lookup.
2511 if (QualifiedNameLookup
) {
2512 ShadowContextRAII
Shadow(Visited
);
2513 DeclContext::udir_iterator I
, E
;
2514 for (llvm::tie(I
, E
) = Ctx
->getUsingDirectives(); I
!= E
; ++I
) {
2515 LookupVisibleDecls((*I
)->getNominatedNamespace(), Result
,
2516 QualifiedNameLookup
, InBaseClass
, Consumer
, Visited
);
2520 // Traverse the contexts of inherited C++ classes.
2521 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Ctx
)) {
2522 if (!Record
->hasDefinition())
2525 for (CXXRecordDecl::base_class_iterator B
= Record
->bases_begin(),
2526 BEnd
= Record
->bases_end();
2528 QualType BaseType
= B
->getType();
2530 // Don't look into dependent bases, because name lookup can't look
2532 if (BaseType
->isDependentType())
2535 const RecordType
*Record
= BaseType
->getAs
<RecordType
>();
2539 // FIXME: It would be nice to be able to determine whether referencing
2540 // a particular member would be ambiguous. For example, given
2542 // struct A { int member; };
2543 // struct B { int member; };
2544 // struct C : A, B { };
2546 // void f(C *c) { c->### }
2548 // accessing 'member' would result in an ambiguity. However, we
2549 // could be smart enough to qualify the member with the base
2558 // Find results in this base class (and its bases).
2559 ShadowContextRAII
Shadow(Visited
);
2560 LookupVisibleDecls(Record
->getDecl(), Result
, QualifiedNameLookup
,
2561 true, Consumer
, Visited
);
2565 // Traverse the contexts of Objective-C classes.
2566 if (ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(Ctx
)) {
2567 // Traverse categories.
2568 for (ObjCCategoryDecl
*Category
= IFace
->getCategoryList();
2569 Category
; Category
= Category
->getNextClassCategory()) {
2570 ShadowContextRAII
Shadow(Visited
);
2571 LookupVisibleDecls(Category
, Result
, QualifiedNameLookup
, false,
2575 // Traverse protocols.
2576 for (ObjCInterfaceDecl::all_protocol_iterator
2577 I
= IFace
->all_referenced_protocol_begin(),
2578 E
= IFace
->all_referenced_protocol_end(); I
!= E
; ++I
) {
2579 ShadowContextRAII
Shadow(Visited
);
2580 LookupVisibleDecls(*I
, Result
, QualifiedNameLookup
, false, Consumer
,
2584 // Traverse the superclass.
2585 if (IFace
->getSuperClass()) {
2586 ShadowContextRAII
Shadow(Visited
);
2587 LookupVisibleDecls(IFace
->getSuperClass(), Result
, QualifiedNameLookup
,
2588 true, Consumer
, Visited
);
2591 // If there is an implementation, traverse it. We do this to find
2592 // synthesized ivars.
2593 if (IFace
->getImplementation()) {
2594 ShadowContextRAII
Shadow(Visited
);
2595 LookupVisibleDecls(IFace
->getImplementation(), Result
,
2596 QualifiedNameLookup
, true, Consumer
, Visited
);
2598 } else if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Ctx
)) {
2599 for (ObjCProtocolDecl::protocol_iterator I
= Protocol
->protocol_begin(),
2600 E
= Protocol
->protocol_end(); I
!= E
; ++I
) {
2601 ShadowContextRAII
Shadow(Visited
);
2602 LookupVisibleDecls(*I
, Result
, QualifiedNameLookup
, false, Consumer
,
2605 } else if (ObjCCategoryDecl
*Category
= dyn_cast
<ObjCCategoryDecl
>(Ctx
)) {
2606 for (ObjCCategoryDecl::protocol_iterator I
= Category
->protocol_begin(),
2607 E
= Category
->protocol_end(); I
!= E
; ++I
) {
2608 ShadowContextRAII
Shadow(Visited
);
2609 LookupVisibleDecls(*I
, Result
, QualifiedNameLookup
, false, Consumer
,
2613 // If there is an implementation, traverse it.
2614 if (Category
->getImplementation()) {
2615 ShadowContextRAII
Shadow(Visited
);
2616 LookupVisibleDecls(Category
->getImplementation(), Result
,
2617 QualifiedNameLookup
, true, Consumer
, Visited
);
2622 static void LookupVisibleDecls(Scope
*S
, LookupResult
&Result
,
2623 UnqualUsingDirectiveSet
&UDirs
,
2624 VisibleDeclConsumer
&Consumer
,
2625 VisibleDeclsRecord
&Visited
) {
2629 if (!S
->getEntity() ||
2631 !Visited
.alreadyVisitedContext((DeclContext
*)S
->getEntity())) ||
2632 ((DeclContext
*)S
->getEntity())->isFunctionOrMethod()) {
2633 // Walk through the declarations in this Scope.
2634 for (Scope::decl_iterator D
= S
->decl_begin(), DEnd
= S
->decl_end();
2636 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(*D
))
2637 if (Result
.isAcceptableDecl(ND
)) {
2638 Consumer
.FoundDecl(ND
, Visited
.checkHidden(ND
), false);
2644 // FIXME: C++ [temp.local]p8
2645 DeclContext
*Entity
= 0;
2646 if (S
->getEntity()) {
2647 // Look into this scope's declaration context, along with any of its
2648 // parent lookup contexts (e.g., enclosing classes), up to the point
2649 // where we hit the context stored in the next outer scope.
2650 Entity
= (DeclContext
*)S
->getEntity();
2651 DeclContext
*OuterCtx
= findOuterContext(S
).first
; // FIXME
2653 for (DeclContext
*Ctx
= Entity
; Ctx
&& !Ctx
->Equals(OuterCtx
);
2654 Ctx
= Ctx
->getLookupParent()) {
2655 if (ObjCMethodDecl
*Method
= dyn_cast
<ObjCMethodDecl
>(Ctx
)) {
2656 if (Method
->isInstanceMethod()) {
2657 // For instance methods, look for ivars in the method's interface.
2658 LookupResult
IvarResult(Result
.getSema(), Result
.getLookupName(),
2659 Result
.getNameLoc(), Sema::LookupMemberName
);
2660 if (ObjCInterfaceDecl
*IFace
= Method
->getClassInterface()) {
2661 LookupVisibleDecls(IFace
, IvarResult
, /*QualifiedNameLookup=*/false,
2662 /*InBaseClass=*/false, Consumer
, Visited
);
2664 // Look for properties from which we can synthesize ivars, if
2666 if (Result
.getSema().getLangOptions().ObjCNonFragileABI2
&&
2667 IFace
->getImplementation() &&
2668 Result
.getLookupKind() == Sema::LookupOrdinaryName
) {
2669 for (ObjCInterfaceDecl::prop_iterator
2670 P
= IFace
->prop_begin(),
2671 PEnd
= IFace
->prop_end();
2673 if (Result
.getSema().canSynthesizeProvisionalIvar(*P
) &&
2674 !IFace
->lookupInstanceVariable((*P
)->getIdentifier())) {
2675 Consumer
.FoundDecl(*P
, Visited
.checkHidden(*P
), false);
2683 // We've already performed all of the name lookup that we need
2684 // to for Objective-C methods; the next context will be the
2689 if (Ctx
->isFunctionOrMethod())
2692 LookupVisibleDecls(Ctx
, Result
, /*QualifiedNameLookup=*/false,
2693 /*InBaseClass=*/false, Consumer
, Visited
);
2695 } else if (!S
->getParent()) {
2696 // Look into the translation unit scope. We walk through the translation
2697 // unit's declaration context, because the Scope itself won't have all of
2698 // the declarations if we loaded a precompiled header.
2699 // FIXME: We would like the translation unit's Scope object to point to the
2700 // translation unit, so we don't need this special "if" branch. However,
2701 // doing so would force the normal C++ name-lookup code to look into the
2702 // translation unit decl when the IdentifierInfo chains would suffice.
2703 // Once we fix that problem (which is part of a more general "don't look
2704 // in DeclContexts unless we have to" optimization), we can eliminate this.
2705 Entity
= Result
.getSema().Context
.getTranslationUnitDecl();
2706 LookupVisibleDecls(Entity
, Result
, /*QualifiedNameLookup=*/false,
2707 /*InBaseClass=*/false, Consumer
, Visited
);
2711 // Lookup visible declarations in any namespaces found by using
2713 UnqualUsingDirectiveSet::const_iterator UI
, UEnd
;
2714 llvm::tie(UI
, UEnd
) = UDirs
.getNamespacesFor(Entity
);
2715 for (; UI
!= UEnd
; ++UI
)
2716 LookupVisibleDecls(const_cast<DeclContext
*>(UI
->getNominatedNamespace()),
2717 Result
, /*QualifiedNameLookup=*/false,
2718 /*InBaseClass=*/false, Consumer
, Visited
);
2721 // Lookup names in the parent scope.
2722 ShadowContextRAII
Shadow(Visited
);
2723 LookupVisibleDecls(S
->getParent(), Result
, UDirs
, Consumer
, Visited
);
2726 void Sema::LookupVisibleDecls(Scope
*S
, LookupNameKind Kind
,
2727 VisibleDeclConsumer
&Consumer
,
2728 bool IncludeGlobalScope
) {
2729 // Determine the set of using directives available during
2730 // unqualified name lookup.
2732 UnqualUsingDirectiveSet UDirs
;
2733 if (getLangOptions().CPlusPlus
) {
2734 // Find the first namespace or translation-unit scope.
2735 while (S
&& !isNamespaceOrTranslationUnitScope(S
))
2738 UDirs
.visitScopeChain(Initial
, S
);
2742 // Look for visible declarations.
2743 LookupResult
Result(*this, DeclarationName(), SourceLocation(), Kind
);
2744 VisibleDeclsRecord Visited
;
2745 if (!IncludeGlobalScope
)
2746 Visited
.visitedContext(Context
.getTranslationUnitDecl());
2747 ShadowContextRAII
Shadow(Visited
);
2748 ::LookupVisibleDecls(Initial
, Result
, UDirs
, Consumer
, Visited
);
2751 void Sema::LookupVisibleDecls(DeclContext
*Ctx
, LookupNameKind Kind
,
2752 VisibleDeclConsumer
&Consumer
,
2753 bool IncludeGlobalScope
) {
2754 LookupResult
Result(*this, DeclarationName(), SourceLocation(), Kind
);
2755 VisibleDeclsRecord Visited
;
2756 if (!IncludeGlobalScope
)
2757 Visited
.visitedContext(Context
.getTranslationUnitDecl());
2758 ShadowContextRAII
Shadow(Visited
);
2759 ::LookupVisibleDecls(Ctx
, Result
, /*QualifiedNameLookup=*/true,
2760 /*InBaseClass=*/false, Consumer
, Visited
);
2763 LabelDecl
*Sema::LookupOrCreateLabel(IdentifierInfo
*II
, SourceLocation Loc
) {
2764 // Do a lookup to see if we have a label with this name already.
2765 NamedDecl
*Res
= LookupSingleName(CurScope
, II
, Loc
, LookupLabel
,
2766 NotForRedeclaration
);
2767 // If we found a label, check to see if it is in the same context as us. When
2768 // in a Block, we don't want to reuse a label in an enclosing function.
2769 if (Res
&& Res
->getDeclContext() != CurContext
)
2773 // If not forward referenced or defined already, create the backing decl.
2774 Res
= LabelDecl::Create(Context
, CurContext
, Loc
, II
);
2775 PushOnScopeChains(Res
, CurScope
->getFnParent(), true);
2778 return cast
<LabelDecl
>(Res
);
2781 //===----------------------------------------------------------------------===//
2783 //===----------------------------------------------------------------------===//
2786 class TypoCorrectionConsumer
: public VisibleDeclConsumer
{
2787 /// \brief The name written that is a typo in the source.
2788 llvm::StringRef Typo
;
2790 /// \brief The results found that have the smallest edit distance
2791 /// found (so far) with the typo name.
2793 /// The boolean value indicates whether there is a keyword with this name.
2794 llvm::StringMap
<bool, llvm::BumpPtrAllocator
> BestResults
;
2796 /// \brief The best edit distance found so far.
2797 unsigned BestEditDistance
;
2800 explicit TypoCorrectionConsumer(IdentifierInfo
*Typo
)
2801 : Typo(Typo
->getName()),
2802 BestEditDistance((std::numeric_limits
<unsigned>::max
)()) { }
2804 virtual void FoundDecl(NamedDecl
*ND
, NamedDecl
*Hiding
, bool InBaseClass
);
2805 void FoundName(llvm::StringRef Name
);
2806 void addKeywordResult(ASTContext
&Context
, llvm::StringRef Keyword
);
2808 typedef llvm::StringMap
<bool, llvm::BumpPtrAllocator
>::iterator iterator
;
2809 iterator
begin() { return BestResults
.begin(); }
2810 iterator
end() { return BestResults
.end(); }
2811 void erase(iterator I
) { BestResults
.erase(I
); }
2812 unsigned size() const { return BestResults
.size(); }
2813 bool empty() const { return BestResults
.empty(); }
2815 bool &operator[](llvm::StringRef Name
) {
2816 return BestResults
[Name
];
2819 unsigned getBestEditDistance() const { return BestEditDistance
; }
2824 void TypoCorrectionConsumer::FoundDecl(NamedDecl
*ND
, NamedDecl
*Hiding
,
2826 // Don't consider hidden names for typo correction.
2830 // Only consider entities with identifiers for names, ignoring
2831 // special names (constructors, overloaded operators, selectors,
2833 IdentifierInfo
*Name
= ND
->getIdentifier();
2837 FoundName(Name
->getName());
2840 void TypoCorrectionConsumer::FoundName(llvm::StringRef Name
) {
2841 using namespace std
;
2843 // Use a simple length-based heuristic to determine the minimum possible
2844 // edit distance. If the minimum isn't good enough, bail out early.
2845 unsigned MinED
= abs((int)Name
.size() - (int)Typo
.size());
2846 if (MinED
> BestEditDistance
|| (MinED
&& Typo
.size() / MinED
< 3))
2849 // Compute an upper bound on the allowable edit distance, so that the
2850 // edit-distance algorithm can short-circuit.
2851 unsigned UpperBound
= min(unsigned((Typo
.size() + 2) / 3), BestEditDistance
);
2853 // Compute the edit distance between the typo and the name of this
2854 // entity. If this edit distance is not worse than the best edit
2855 // distance we've seen so far, add it to the list of results.
2856 unsigned ED
= Typo
.edit_distance(Name
, true, UpperBound
);
2860 if (ED
< BestEditDistance
) {
2861 // This result is better than any we've seen before; clear out
2862 // the previous results.
2863 BestResults
.clear();
2864 BestEditDistance
= ED
;
2865 } else if (ED
> BestEditDistance
) {
2866 // This result is worse than the best results we've seen so far;
2871 // Add this name to the list of results. By not assigning a value, we
2872 // keep the current value if we've seen this name before (either as a
2873 // keyword or as a declaration), or get the default value (not a keyword)
2874 // if we haven't seen it before.
2875 (void)BestResults
[Name
];
2878 void TypoCorrectionConsumer::addKeywordResult(ASTContext
&Context
,
2879 llvm::StringRef Keyword
) {
2880 // Compute the edit distance between the typo and this keyword.
2881 // If this edit distance is not worse than the best edit
2882 // distance we've seen so far, add it to the list of results.
2883 unsigned ED
= Typo
.edit_distance(Keyword
);
2884 if (ED
< BestEditDistance
) {
2885 BestResults
.clear();
2886 BestEditDistance
= ED
;
2887 } else if (ED
> BestEditDistance
) {
2888 // This result is worse than the best results we've seen so far;
2893 BestResults
[Keyword
] = true;
2896 /// \brief Perform name lookup for a possible result for typo correction.
2897 static void LookupPotentialTypoResult(Sema
&SemaRef
,
2899 IdentifierInfo
*Name
,
2900 Scope
*S
, CXXScopeSpec
*SS
,
2901 DeclContext
*MemberContext
,
2902 bool EnteringContext
,
2903 Sema::CorrectTypoContext CTC
) {
2904 Res
.suppressDiagnostics();
2906 Res
.setLookupName(Name
);
2907 if (MemberContext
) {
2908 if (ObjCInterfaceDecl
*Class
= dyn_cast
<ObjCInterfaceDecl
>(MemberContext
)) {
2909 if (CTC
== Sema::CTC_ObjCIvarLookup
) {
2910 if (ObjCIvarDecl
*Ivar
= Class
->lookupInstanceVariable(Name
)) {
2917 if (ObjCPropertyDecl
*Prop
= Class
->FindPropertyDeclaration(Name
)) {
2924 SemaRef
.LookupQualifiedName(Res
, MemberContext
);
2928 SemaRef
.LookupParsedName(Res
, S
, SS
, /*AllowBuiltinCreation=*/false,
2931 // Fake ivar lookup; this should really be part of
2932 // LookupParsedName.
2933 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl()) {
2934 if (Method
->isInstanceMethod() && Method
->getClassInterface() &&
2936 (Res
.isSingleResult() &&
2937 Res
.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
2938 if (ObjCIvarDecl
*IV
2939 = Method
->getClassInterface()->lookupInstanceVariable(Name
)) {
2947 /// \brief Try to "correct" a typo in the source code by finding
2948 /// visible declarations whose names are similar to the name that was
2949 /// present in the source code.
2951 /// \param Res the \c LookupResult structure that contains the name
2952 /// that was present in the source code along with the name-lookup
2953 /// criteria used to search for the name. On success, this structure
2954 /// will contain the results of name lookup.
2956 /// \param S the scope in which name lookup occurs.
2958 /// \param SS the nested-name-specifier that precedes the name we're
2959 /// looking for, if present.
2961 /// \param MemberContext if non-NULL, the context in which to look for
2962 /// a member access expression.
2964 /// \param EnteringContext whether we're entering the context described by
2965 /// the nested-name-specifier SS.
2967 /// \param CTC The context in which typo correction occurs, which impacts the
2968 /// set of keywords permitted.
2970 /// \param OPT when non-NULL, the search for visible declarations will
2971 /// also walk the protocols in the qualified interfaces of \p OPT.
2973 /// \returns the corrected name if the typo was corrected, otherwise returns an
2974 /// empty \c DeclarationName. When a typo was corrected, the result structure
2975 /// may contain the results of name lookup for the correct name or it may be
2977 DeclarationName
Sema::CorrectTypo(LookupResult
&Res
, Scope
*S
, CXXScopeSpec
*SS
,
2978 DeclContext
*MemberContext
,
2979 bool EnteringContext
,
2980 CorrectTypoContext CTC
,
2981 const ObjCObjectPointerType
*OPT
) {
2982 if (Diags
.hasFatalErrorOccurred() || !getLangOptions().SpellChecking
)
2983 return DeclarationName();
2985 // We only attempt to correct typos for identifiers.
2986 IdentifierInfo
*Typo
= Res
.getLookupName().getAsIdentifierInfo();
2988 return DeclarationName();
2990 // If the scope specifier itself was invalid, don't try to correct
2992 if (SS
&& SS
->isInvalid())
2993 return DeclarationName();
2995 // Never try to correct typos during template deduction or
2997 if (!ActiveTemplateInstantiations
.empty())
2998 return DeclarationName();
3000 TypoCorrectionConsumer
Consumer(Typo
);
3002 // Perform name lookup to find visible, similarly-named entities.
3003 bool IsUnqualifiedLookup
= false;
3004 if (MemberContext
) {
3005 LookupVisibleDecls(MemberContext
, Res
.getLookupKind(), Consumer
);
3007 // Look in qualified interfaces.
3009 for (ObjCObjectPointerType::qual_iterator
3010 I
= OPT
->qual_begin(), E
= OPT
->qual_end();
3012 LookupVisibleDecls(*I
, Res
.getLookupKind(), Consumer
);
3014 } else if (SS
&& SS
->isSet()) {
3015 DeclContext
*DC
= computeDeclContext(*SS
, EnteringContext
);
3017 return DeclarationName();
3019 // Provide a stop gap for files that are just seriously broken. Trying
3020 // to correct all typos can turn into a HUGE performance penalty, causing
3021 // some files to take minutes to get rejected by the parser.
3022 if (TyposCorrected
+ UnqualifiedTyposCorrected
.size() >= 20)
3023 return DeclarationName();
3026 LookupVisibleDecls(DC
, Res
.getLookupKind(), Consumer
);
3028 IsUnqualifiedLookup
= true;
3029 UnqualifiedTyposCorrectedMap::iterator Cached
3030 = UnqualifiedTyposCorrected
.find(Typo
);
3031 if (Cached
== UnqualifiedTyposCorrected
.end()) {
3032 // Provide a stop gap for files that are just seriously broken. Trying
3033 // to correct all typos can turn into a HUGE performance penalty, causing
3034 // some files to take minutes to get rejected by the parser.
3035 if (TyposCorrected
+ UnqualifiedTyposCorrected
.size() >= 20)
3036 return DeclarationName();
3038 // For unqualified lookup, look through all of the names that we have
3039 // seen in this translation unit.
3040 for (IdentifierTable::iterator I
= Context
.Idents
.begin(),
3041 IEnd
= Context
.Idents
.end();
3043 Consumer
.FoundName(I
->getKey());
3045 // Walk through identifiers in external identifier sources.
3046 if (IdentifierInfoLookup
*External
3047 = Context
.Idents
.getExternalIdentifierLookup()) {
3048 llvm::OwningPtr
<IdentifierIterator
> Iter(External
->getIdentifiers());
3050 llvm::StringRef Name
= Iter
->Next();
3054 Consumer
.FoundName(Name
);
3058 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3059 // end up adding the keyword below.
3060 if (Cached
->second
.first
.empty())
3061 return DeclarationName();
3063 if (!Cached
->second
.second
)
3064 Consumer
.FoundName(Cached
->second
.first
);
3068 // Add context-dependent keywords.
3069 bool WantTypeSpecifiers
= false;
3070 bool WantExpressionKeywords
= false;
3071 bool WantCXXNamedCasts
= false;
3072 bool WantRemainingKeywords
= false;
3075 WantTypeSpecifiers
= true;
3076 WantExpressionKeywords
= true;
3077 WantCXXNamedCasts
= true;
3078 WantRemainingKeywords
= true;
3080 if (ObjCMethodDecl
*Method
= getCurMethodDecl())
3081 if (Method
->getClassInterface() &&
3082 Method
->getClassInterface()->getSuperClass())
3083 Consumer
.addKeywordResult(Context
, "super");
3087 case CTC_NoKeywords
:
3091 WantTypeSpecifiers
= true;
3094 case CTC_ObjCMessageReceiver
:
3095 Consumer
.addKeywordResult(Context
, "super");
3096 // Fall through to handle message receivers like expressions.
3098 case CTC_Expression
:
3099 if (getLangOptions().CPlusPlus
)
3100 WantTypeSpecifiers
= true;
3101 WantExpressionKeywords
= true;
3102 // Fall through to get C++ named casts.
3105 WantCXXNamedCasts
= true;
3108 case CTC_ObjCPropertyLookup
:
3109 // FIXME: Add "isa"?
3112 case CTC_MemberLookup
:
3113 if (getLangOptions().CPlusPlus
)
3114 Consumer
.addKeywordResult(Context
, "template");
3117 case CTC_ObjCIvarLookup
:
3121 if (WantTypeSpecifiers
) {
3122 // Add type-specifier keywords to the set of results.
3123 const char *CTypeSpecs
[] = {
3124 "char", "const", "double", "enum", "float", "int", "long", "short",
3125 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3126 "_Complex", "_Imaginary",
3127 // storage-specifiers as well
3128 "extern", "inline", "static", "typedef"
3131 const unsigned NumCTypeSpecs
= sizeof(CTypeSpecs
) / sizeof(CTypeSpecs
[0]);
3132 for (unsigned I
= 0; I
!= NumCTypeSpecs
; ++I
)
3133 Consumer
.addKeywordResult(Context
, CTypeSpecs
[I
]);
3135 if (getLangOptions().C99
)
3136 Consumer
.addKeywordResult(Context
, "restrict");
3137 if (getLangOptions().Bool
|| getLangOptions().CPlusPlus
)
3138 Consumer
.addKeywordResult(Context
, "bool");
3140 if (getLangOptions().CPlusPlus
) {
3141 Consumer
.addKeywordResult(Context
, "class");
3142 Consumer
.addKeywordResult(Context
, "typename");
3143 Consumer
.addKeywordResult(Context
, "wchar_t");
3145 if (getLangOptions().CPlusPlus0x
) {
3146 Consumer
.addKeywordResult(Context
, "char16_t");
3147 Consumer
.addKeywordResult(Context
, "char32_t");
3148 Consumer
.addKeywordResult(Context
, "constexpr");
3149 Consumer
.addKeywordResult(Context
, "decltype");
3150 Consumer
.addKeywordResult(Context
, "thread_local");
3154 if (getLangOptions().GNUMode
)
3155 Consumer
.addKeywordResult(Context
, "typeof");
3158 if (WantCXXNamedCasts
&& getLangOptions().CPlusPlus
) {
3159 Consumer
.addKeywordResult(Context
, "const_cast");
3160 Consumer
.addKeywordResult(Context
, "dynamic_cast");
3161 Consumer
.addKeywordResult(Context
, "reinterpret_cast");
3162 Consumer
.addKeywordResult(Context
, "static_cast");
3165 if (WantExpressionKeywords
) {
3166 Consumer
.addKeywordResult(Context
, "sizeof");
3167 if (getLangOptions().Bool
|| getLangOptions().CPlusPlus
) {
3168 Consumer
.addKeywordResult(Context
, "false");
3169 Consumer
.addKeywordResult(Context
, "true");
3172 if (getLangOptions().CPlusPlus
) {
3173 const char *CXXExprs
[] = {
3174 "delete", "new", "operator", "throw", "typeid"
3176 const unsigned NumCXXExprs
= sizeof(CXXExprs
) / sizeof(CXXExprs
[0]);
3177 for (unsigned I
= 0; I
!= NumCXXExprs
; ++I
)
3178 Consumer
.addKeywordResult(Context
, CXXExprs
[I
]);
3180 if (isa
<CXXMethodDecl
>(CurContext
) &&
3181 cast
<CXXMethodDecl
>(CurContext
)->isInstance())
3182 Consumer
.addKeywordResult(Context
, "this");
3184 if (getLangOptions().CPlusPlus0x
) {
3185 Consumer
.addKeywordResult(Context
, "alignof");
3186 Consumer
.addKeywordResult(Context
, "nullptr");
3191 if (WantRemainingKeywords
) {
3192 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3194 const char *CStmts
[] = {
3195 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3196 const unsigned NumCStmts
= sizeof(CStmts
) / sizeof(CStmts
[0]);
3197 for (unsigned I
= 0; I
!= NumCStmts
; ++I
)
3198 Consumer
.addKeywordResult(Context
, CStmts
[I
]);
3200 if (getLangOptions().CPlusPlus
) {
3201 Consumer
.addKeywordResult(Context
, "catch");
3202 Consumer
.addKeywordResult(Context
, "try");
3205 if (S
&& S
->getBreakParent())
3206 Consumer
.addKeywordResult(Context
, "break");
3208 if (S
&& S
->getContinueParent())
3209 Consumer
.addKeywordResult(Context
, "continue");
3211 if (!getCurFunction()->SwitchStack
.empty()) {
3212 Consumer
.addKeywordResult(Context
, "case");
3213 Consumer
.addKeywordResult(Context
, "default");
3216 if (getLangOptions().CPlusPlus
) {
3217 Consumer
.addKeywordResult(Context
, "namespace");
3218 Consumer
.addKeywordResult(Context
, "template");
3221 if (S
&& S
->isClassScope()) {
3222 Consumer
.addKeywordResult(Context
, "explicit");
3223 Consumer
.addKeywordResult(Context
, "friend");
3224 Consumer
.addKeywordResult(Context
, "mutable");
3225 Consumer
.addKeywordResult(Context
, "private");
3226 Consumer
.addKeywordResult(Context
, "protected");
3227 Consumer
.addKeywordResult(Context
, "public");
3228 Consumer
.addKeywordResult(Context
, "virtual");
3232 if (getLangOptions().CPlusPlus
) {
3233 Consumer
.addKeywordResult(Context
, "using");
3235 if (getLangOptions().CPlusPlus0x
)
3236 Consumer
.addKeywordResult(Context
, "static_assert");
3240 // If we haven't found anything, we're done.
3241 if (Consumer
.empty()) {
3242 // If this was an unqualified lookup, note that no correction was found.
3243 if (IsUnqualifiedLookup
)
3244 (void)UnqualifiedTyposCorrected
[Typo
];
3246 return DeclarationName();
3249 // Make sure that the user typed at least 3 characters for each correction
3250 // made. Otherwise, we don't even both looking at the results.
3252 // We also suppress exact matches; those should be handled by a
3253 // different mechanism (e.g., one that introduces qualification in
3255 unsigned ED
= Consumer
.getBestEditDistance();
3256 if (ED
> 0 && Typo
->getName().size() / ED
< 3) {
3257 // If this was an unqualified lookup, note that no correction was found.
3258 if (IsUnqualifiedLookup
)
3259 (void)UnqualifiedTyposCorrected
[Typo
];
3261 return DeclarationName();
3264 // Weed out any names that could not be found by name lookup.
3265 bool LastLookupWasAccepted
= false;
3266 for (TypoCorrectionConsumer::iterator I
= Consumer
.begin(),
3267 IEnd
= Consumer
.end();
3268 I
!= IEnd
; /* Increment in loop. */) {
3269 // Keywords are always found.
3275 // Perform name lookup on this name.
3276 IdentifierInfo
*Name
= &Context
.Idents
.get(I
->getKey());
3277 LookupPotentialTypoResult(*this, Res
, Name
, S
, SS
, MemberContext
,
3278 EnteringContext
, CTC
);
3280 switch (Res
.getResultKind()) {
3281 case LookupResult::NotFound
:
3282 case LookupResult::NotFoundInCurrentInstantiation
:
3283 case LookupResult::Ambiguous
:
3284 // We didn't find this name in our scope, or didn't like what we found;
3286 Res
.suppressDiagnostics();
3288 TypoCorrectionConsumer::iterator Next
= I
;
3293 LastLookupWasAccepted
= false;
3296 case LookupResult::Found
:
3297 case LookupResult::FoundOverloaded
:
3298 case LookupResult::FoundUnresolvedValue
:
3300 LastLookupWasAccepted
= true;
3304 if (Res
.isAmbiguous()) {
3305 // We don't deal with ambiguities.
3306 Res
.suppressDiagnostics();
3308 return DeclarationName();
3312 // If only a single name remains, return that result.
3313 if (Consumer
.size() == 1) {
3314 IdentifierInfo
*Name
= &Context
.Idents
.get(Consumer
.begin()->getKey());
3315 if (Consumer
.begin()->second
) {
3316 Res
.suppressDiagnostics();
3319 // Don't correct to a keyword that's the same as the typo; the keyword
3320 // wasn't actually in scope.
3322 Res
.setLookupName(Typo
);
3323 return DeclarationName();
3326 } else if (!LastLookupWasAccepted
) {
3327 // Perform name lookup on this name.
3328 LookupPotentialTypoResult(*this, Res
, Name
, S
, SS
, MemberContext
,
3329 EnteringContext
, CTC
);
3332 // Record the correction for unqualified lookup.
3333 if (IsUnqualifiedLookup
)
3334 UnqualifiedTyposCorrected
[Typo
]
3335 = std::make_pair(Name
->getName(), Consumer
.begin()->second
);
3337 return &Context
.Idents
.get(Consumer
.begin()->getKey());
3339 else if (Consumer
.size() > 1 && CTC
== CTC_ObjCMessageReceiver
3340 && Consumer
["super"]) {
3341 // Prefix 'super' when we're completing in a message-receiver
3343 Res
.suppressDiagnostics();
3346 // Don't correct to a keyword that's the same as the typo; the keyword
3347 // wasn't actually in scope.
3349 Res
.setLookupName(Typo
);
3350 return DeclarationName();
3353 // Record the correction for unqualified lookup.
3354 if (IsUnqualifiedLookup
)
3355 UnqualifiedTyposCorrected
[Typo
]
3356 = std::make_pair("super", Consumer
.begin()->second
);
3358 return &Context
.Idents
.get("super");
3361 Res
.suppressDiagnostics();
3362 Res
.setLookupName(Typo
);
3364 // Record the correction for unqualified lookup.
3365 if (IsUnqualifiedLookup
)
3366 (void)UnqualifiedTyposCorrected
[Typo
];
3368 return DeclarationName();