Keep the source location of the selector in ObjCMessageExpr.
[clang.git] / lib / Sema / SemaLookup.cpp
blob6ff9cc69f1cf5d9bce2a444251a1c5604ac58ada
1 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements name lookup for C, C++, Objective-C, and
11 // Objective-C++.
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"
36 #include <limits>
37 #include <list>
38 #include <set>
39 #include <vector>
40 #include <iterator>
41 #include <utility>
42 #include <algorithm>
44 using namespace clang;
45 using namespace sema;
47 namespace {
48 class UnqualUsingEntry {
49 const DeclContext *Nominated;
50 const DeclContext *CommonAncestor;
52 public:
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 {
63 return Nominated;
66 // Sort by the pointer value of the common ancestor.
67 struct Comparator {
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
83 /// lookup.
84 class UnqualUsingDirectiveSet {
85 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy;
87 ListTy list;
88 llvm::SmallPtrSet<DeclContext*, 8> visited;
90 public:
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);
106 } else {
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))
125 return;
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))
136 return;
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;
147 while (true) {
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);
154 queue.push_back(NS);
158 if (queue.empty())
159 return;
161 DC = queue.back();
162 queue.pop_back();
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
172 // the first.
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));
184 void done() {
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,
204 bool CPlusPlus,
205 bool Redeclaration) {
206 unsigned IDNS = 0;
207 switch (NameKind) {
208 case Sema::LookupOrdinaryName:
209 case Sema::LookupRedeclarationWithLinkage:
210 IDNS = Decl::IDNS_Ordinary;
211 if (CPlusPlus) {
212 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
213 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
215 break;
217 case Sema::LookupOperatorName:
218 // Operator lookup is its own crazy thing; it is not the same
219 // as (e.g.) looking up an operator name for redeclaration.
220 assert(!Redeclaration && "cannot do redeclaration operator lookup");
221 IDNS = Decl::IDNS_NonMemberOperator;
222 break;
224 case Sema::LookupTagName:
225 if (CPlusPlus) {
226 IDNS = Decl::IDNS_Type;
228 // When looking for a redeclaration of a tag name, we add:
229 // 1) TagFriend to find undeclared friend decls
230 // 2) Namespace because they can't "overload" with tag decls.
231 // 3) Tag because it includes class templates, which can't
232 // "overload" with tag decls.
233 if (Redeclaration)
234 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
235 } else {
236 IDNS = Decl::IDNS_Tag;
238 break;
240 case Sema::LookupMemberName:
241 IDNS = Decl::IDNS_Member;
242 if (CPlusPlus)
243 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
244 break;
246 case Sema::LookupNestedNameSpecifierName:
247 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
248 break;
250 case Sema::LookupNamespaceName:
251 IDNS = Decl::IDNS_Namespace;
252 break;
254 case Sema::LookupUsingDeclName:
255 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag
256 | Decl::IDNS_Member | Decl::IDNS_Using;
257 break;
259 case Sema::LookupObjCProtocolName:
260 IDNS = Decl::IDNS_ObjCProtocol;
261 break;
263 case Sema::LookupAnyName:
264 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
265 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
266 | Decl::IDNS_Type;
267 break;
269 return IDNS;
272 void LookupResult::configure() {
273 IDNS = getIDNS(LookupKind,
274 SemaRef.getLangOptions().CPlusPlus,
275 isForRedeclaration());
277 // If we're looking for one of the allocation or deallocation
278 // operators, make sure that the implicitly-declared new and delete
279 // operators can be found.
280 if (!isForRedeclaration()) {
281 switch (NameInfo.getName().getCXXOverloadedOperator()) {
282 case OO_New:
283 case OO_Delete:
284 case OO_Array_New:
285 case OO_Array_Delete:
286 SemaRef.DeclareGlobalNewDelete();
287 break;
289 default:
290 break;
295 void LookupResult::sanity() const {
296 assert(ResultKind != NotFound || Decls.size() == 0);
297 assert(ResultKind != Found || Decls.size() == 1);
298 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
299 (Decls.size() == 1 &&
300 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
301 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
302 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
303 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
304 Ambiguity == AmbiguousBaseSubobjectTypes)));
305 assert((Paths != NULL) == (ResultKind == Ambiguous &&
306 (Ambiguity == AmbiguousBaseSubobjectTypes ||
307 Ambiguity == AmbiguousBaseSubobjects)));
310 // Necessary because CXXBasePaths is not complete in Sema.h
311 void LookupResult::deletePaths(CXXBasePaths *Paths) {
312 delete Paths;
315 /// Resolves the result kind of this lookup.
316 void LookupResult::resolveKind() {
317 unsigned N = Decls.size();
319 // Fast case: no possible ambiguity.
320 if (N == 0) {
321 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
322 return;
325 // If there's a single decl, we need to examine it to decide what
326 // kind of lookup this is.
327 if (N == 1) {
328 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
329 if (isa<FunctionTemplateDecl>(D))
330 ResultKind = FoundOverloaded;
331 else if (isa<UnresolvedUsingValueDecl>(D))
332 ResultKind = FoundUnresolvedValue;
333 return;
336 // Don't do any extra resolution if we've already resolved as ambiguous.
337 if (ResultKind == Ambiguous) return;
339 llvm::SmallPtrSet<NamedDecl*, 16> Unique;
340 llvm::SmallPtrSet<QualType, 16> UniqueTypes;
342 bool Ambiguous = false;
343 bool HasTag = false, HasFunction = false, HasNonFunction = false;
344 bool HasFunctionTemplate = false, HasUnresolved = false;
346 unsigned UniqueTagIndex = 0;
348 unsigned I = 0;
349 while (I < N) {
350 NamedDecl *D = Decls[I]->getUnderlyingDecl();
351 D = cast<NamedDecl>(D->getCanonicalDecl());
353 // Redeclarations of types via typedef can occur both within a scope
354 // and, through using declarations and directives, across scopes. There is
355 // no ambiguity if they all refer to the same type, so unique based on the
356 // canonical type.
357 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
358 if (!TD->getDeclContext()->isRecord()) {
359 QualType T = SemaRef.Context.getTypeDeclType(TD);
360 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) {
361 // The type is not unique; pull something off the back and continue
362 // at this index.
363 Decls[I] = Decls[--N];
364 continue;
369 if (!Unique.insert(D)) {
370 // If it's not unique, pull something off the back (and
371 // continue at this index).
372 Decls[I] = Decls[--N];
373 continue;
376 // Otherwise, do some decl type analysis and then continue.
378 if (isa<UnresolvedUsingValueDecl>(D)) {
379 HasUnresolved = true;
380 } else if (isa<TagDecl>(D)) {
381 if (HasTag)
382 Ambiguous = true;
383 UniqueTagIndex = I;
384 HasTag = true;
385 } else if (isa<FunctionTemplateDecl>(D)) {
386 HasFunction = true;
387 HasFunctionTemplate = true;
388 } else if (isa<FunctionDecl>(D)) {
389 HasFunction = true;
390 } else {
391 if (HasNonFunction)
392 Ambiguous = true;
393 HasNonFunction = true;
395 I++;
398 // C++ [basic.scope.hiding]p2:
399 // A class name or enumeration name can be hidden by the name of
400 // an object, function, or enumerator declared in the same
401 // scope. If a class or enumeration name and an object, function,
402 // or enumerator are declared in the same scope (in any order)
403 // with the same name, the class or enumeration name is hidden
404 // wherever the object, function, or enumerator name is visible.
405 // But it's still an error if there are distinct tag types found,
406 // even if they're not visible. (ref?)
407 if (HideTags && HasTag && !Ambiguous &&
408 (HasFunction || HasNonFunction || HasUnresolved)) {
409 if (Decls[UniqueTagIndex]->getDeclContext()->getRedeclContext()->Equals(
410 Decls[UniqueTagIndex? 0 : N-1]->getDeclContext()->getRedeclContext()))
411 Decls[UniqueTagIndex] = Decls[--N];
412 else
413 Ambiguous = true;
416 Decls.set_size(N);
418 if (HasNonFunction && (HasFunction || HasUnresolved))
419 Ambiguous = true;
421 if (Ambiguous)
422 setAmbiguous(LookupResult::AmbiguousReference);
423 else if (HasUnresolved)
424 ResultKind = LookupResult::FoundUnresolvedValue;
425 else if (N > 1 || HasFunctionTemplate)
426 ResultKind = LookupResult::FoundOverloaded;
427 else
428 ResultKind = LookupResult::Found;
431 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
432 CXXBasePaths::const_paths_iterator I, E;
433 DeclContext::lookup_iterator DI, DE;
434 for (I = P.begin(), E = P.end(); I != E; ++I)
435 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI)
436 addDecl(*DI);
439 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
440 Paths = new CXXBasePaths;
441 Paths->swap(P);
442 addDeclsFromBasePaths(*Paths);
443 resolveKind();
444 setAmbiguous(AmbiguousBaseSubobjects);
447 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
448 Paths = new CXXBasePaths;
449 Paths->swap(P);
450 addDeclsFromBasePaths(*Paths);
451 resolveKind();
452 setAmbiguous(AmbiguousBaseSubobjectTypes);
455 void LookupResult::print(llvm::raw_ostream &Out) {
456 Out << Decls.size() << " result(s)";
457 if (isAmbiguous()) Out << ", ambiguous";
458 if (Paths) Out << ", base paths present";
460 for (iterator I = begin(), E = end(); I != E; ++I) {
461 Out << "\n";
462 (*I)->print(Out, 2);
466 /// \brief Lookup a builtin function, when name lookup would otherwise
467 /// fail.
468 static bool LookupBuiltin(Sema &S, LookupResult &R) {
469 Sema::LookupNameKind NameKind = R.getLookupKind();
471 // If we didn't find a use of this identifier, and if the identifier
472 // corresponds to a compiler builtin, create the decl object for the builtin
473 // now, injecting it into translation unit scope, and return it.
474 if (NameKind == Sema::LookupOrdinaryName ||
475 NameKind == Sema::LookupRedeclarationWithLinkage) {
476 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
477 if (II) {
478 // If this is a builtin on this (or all) targets, create the decl.
479 if (unsigned BuiltinID = II->getBuiltinID()) {
480 // In C++, we don't have any predefined library functions like
481 // 'malloc'. Instead, we'll just error.
482 if (S.getLangOptions().CPlusPlus &&
483 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
484 return false;
486 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
487 S.TUScope, R.isForRedeclaration(),
488 R.getNameLoc());
489 if (D)
490 R.addDecl(D);
491 return (D != NULL);
496 return false;
499 /// \brief Determine whether we can declare a special member function within
500 /// the class at this point.
501 static bool CanDeclareSpecialMemberFunction(ASTContext &Context,
502 const CXXRecordDecl *Class) {
503 // Don't do it if the class is invalid.
504 if (Class->isInvalidDecl())
505 return false;
507 // We need to have a definition for the class.
508 if (!Class->getDefinition() || Class->isDependentContext())
509 return false;
511 // We can't be in the middle of defining the class.
512 if (const RecordType *RecordTy
513 = Context.getTypeDeclType(Class)->getAs<RecordType>())
514 return !RecordTy->isBeingDefined();
516 return false;
519 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
520 if (!CanDeclareSpecialMemberFunction(Context, Class))
521 return;
523 // If the default constructor has not yet been declared, do so now.
524 if (!Class->hasDeclaredDefaultConstructor())
525 DeclareImplicitDefaultConstructor(Class);
527 // If the copy constructor has not yet been declared, do so now.
528 if (!Class->hasDeclaredCopyConstructor())
529 DeclareImplicitCopyConstructor(Class);
531 // If the copy assignment operator has not yet been declared, do so now.
532 if (!Class->hasDeclaredCopyAssignment())
533 DeclareImplicitCopyAssignment(Class);
535 // If the destructor has not yet been declared, do so now.
536 if (!Class->hasDeclaredDestructor())
537 DeclareImplicitDestructor(Class);
540 /// \brief Determine whether this is the name of an implicitly-declared
541 /// special member function.
542 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
543 switch (Name.getNameKind()) {
544 case DeclarationName::CXXConstructorName:
545 case DeclarationName::CXXDestructorName:
546 return true;
548 case DeclarationName::CXXOperatorName:
549 return Name.getCXXOverloadedOperator() == OO_Equal;
551 default:
552 break;
555 return false;
558 /// \brief If there are any implicit member functions with the given name
559 /// that need to be declared in the given declaration context, do so.
560 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
561 DeclarationName Name,
562 const DeclContext *DC) {
563 if (!DC)
564 return;
566 switch (Name.getNameKind()) {
567 case DeclarationName::CXXConstructorName:
568 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
569 if (Record->getDefinition() &&
570 CanDeclareSpecialMemberFunction(S.Context, Record)) {
571 if (!Record->hasDeclaredDefaultConstructor())
572 S.DeclareImplicitDefaultConstructor(
573 const_cast<CXXRecordDecl *>(Record));
574 if (!Record->hasDeclaredCopyConstructor())
575 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record));
577 break;
579 case DeclarationName::CXXDestructorName:
580 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
581 if (Record->getDefinition() && !Record->hasDeclaredDestructor() &&
582 CanDeclareSpecialMemberFunction(S.Context, Record))
583 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
584 break;
586 case DeclarationName::CXXOperatorName:
587 if (Name.getCXXOverloadedOperator() != OO_Equal)
588 break;
590 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
591 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() &&
592 CanDeclareSpecialMemberFunction(S.Context, Record))
593 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record));
594 break;
596 default:
597 break;
601 // Adds all qualifying matches for a name within a decl context to the
602 // given lookup result. Returns true if any matches were found.
603 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
604 bool Found = false;
606 // Lazily declare C++ special member functions.
607 if (S.getLangOptions().CPlusPlus)
608 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
610 // Perform lookup into this declaration context.
611 DeclContext::lookup_const_iterator I, E;
612 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) {
613 NamedDecl *D = *I;
614 if (R.isAcceptableDecl(D)) {
615 R.addDecl(D);
616 Found = true;
620 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
621 return true;
623 if (R.getLookupName().getNameKind()
624 != DeclarationName::CXXConversionFunctionName ||
625 R.getLookupName().getCXXNameType()->isDependentType() ||
626 !isa<CXXRecordDecl>(DC))
627 return Found;
629 // C++ [temp.mem]p6:
630 // A specialization of a conversion function template is not found by
631 // name lookup. Instead, any conversion function templates visible in the
632 // context of the use are considered. [...]
633 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
634 if (!Record->isDefinition())
635 return Found;
637 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions();
638 for (UnresolvedSetImpl::iterator U = Unresolved->begin(),
639 UEnd = Unresolved->end(); U != UEnd; ++U) {
640 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
641 if (!ConvTemplate)
642 continue;
644 // When we're performing lookup for the purposes of redeclaration, just
645 // add the conversion function template. When we deduce template
646 // arguments for specializations, we'll end up unifying the return
647 // type of the new declaration with the type of the function template.
648 if (R.isForRedeclaration()) {
649 R.addDecl(ConvTemplate);
650 Found = true;
651 continue;
654 // C++ [temp.mem]p6:
655 // [...] For each such operator, if argument deduction succeeds
656 // (14.9.2.3), the resulting specialization is used as if found by
657 // name lookup.
659 // When referencing a conversion function for any purpose other than
660 // a redeclaration (such that we'll be building an expression with the
661 // result), perform template argument deduction and place the
662 // specialization into the result set. We do this to avoid forcing all
663 // callers to perform special deduction for conversion functions.
664 TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc());
665 FunctionDecl *Specialization = 0;
667 const FunctionProtoType *ConvProto
668 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
669 assert(ConvProto && "Nonsensical conversion function template type");
671 // Compute the type of the function that we would expect the conversion
672 // function to have, if it were to match the name given.
673 // FIXME: Calling convention!
674 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo();
675 QualType ExpectedType
676 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
677 0, 0, ConvProto->isVariadic(),
678 ConvProto->getTypeQuals(),
679 false, false, 0, 0,
680 ConvProtoInfo.withCallingConv(CC_Default));
682 // Perform template argument deduction against the type that we would
683 // expect the function to have.
684 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType,
685 Specialization, Info)
686 == Sema::TDK_Success) {
687 R.addDecl(Specialization);
688 Found = true;
692 return Found;
695 // Performs C++ unqualified lookup into the given file context.
696 static bool
697 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
698 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
700 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
702 // Perform direct name lookup into the LookupCtx.
703 bool Found = LookupDirect(S, R, NS);
705 // Perform direct name lookup into the namespaces nominated by the
706 // using directives whose common ancestor is this namespace.
707 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
708 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS);
710 for (; UI != UEnd; ++UI)
711 if (LookupDirect(S, R, UI->getNominatedNamespace()))
712 Found = true;
714 R.resolveKind();
716 return Found;
719 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
720 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
721 return Ctx->isFileContext();
722 return false;
725 // Find the next outer declaration context from this scope. This
726 // routine actually returns the semantic outer context, which may
727 // differ from the lexical context (encoded directly in the Scope
728 // stack) when we are parsing a member of a class template. In this
729 // case, the second element of the pair will be true, to indicate that
730 // name lookup should continue searching in this semantic context when
731 // it leaves the current template parameter scope.
732 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
733 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
734 DeclContext *Lexical = 0;
735 for (Scope *OuterS = S->getParent(); OuterS;
736 OuterS = OuterS->getParent()) {
737 if (OuterS->getEntity()) {
738 Lexical = static_cast<DeclContext *>(OuterS->getEntity());
739 break;
743 // C++ [temp.local]p8:
744 // In the definition of a member of a class template that appears
745 // outside of the namespace containing the class template
746 // definition, the name of a template-parameter hides the name of
747 // a member of this namespace.
749 // Example:
751 // namespace N {
752 // class C { };
754 // template<class T> class B {
755 // void f(T);
756 // };
757 // }
759 // template<class C> void N::B<C>::f(C) {
760 // C b; // C is the template parameter, not N::C
761 // }
763 // In this example, the lexical context we return is the
764 // TranslationUnit, while the semantic context is the namespace N.
765 if (!Lexical || !DC || !S->getParent() ||
766 !S->getParent()->isTemplateParamScope())
767 return std::make_pair(Lexical, false);
769 // Find the outermost template parameter scope.
770 // For the example, this is the scope for the template parameters of
771 // template<class C>.
772 Scope *OutermostTemplateScope = S->getParent();
773 while (OutermostTemplateScope->getParent() &&
774 OutermostTemplateScope->getParent()->isTemplateParamScope())
775 OutermostTemplateScope = OutermostTemplateScope->getParent();
777 // Find the namespace context in which the original scope occurs. In
778 // the example, this is namespace N.
779 DeclContext *Semantic = DC;
780 while (!Semantic->isFileContext())
781 Semantic = Semantic->getParent();
783 // Find the declaration context just outside of the template
784 // parameter scope. This is the context in which the template is
785 // being lexically declaration (a namespace context). In the
786 // example, this is the global scope.
787 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
788 Lexical->Encloses(Semantic))
789 return std::make_pair(Semantic, true);
791 return std::make_pair(Lexical, false);
794 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
795 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup");
797 DeclarationName Name = R.getLookupName();
799 // If this is the name of an implicitly-declared special member function,
800 // go through the scope stack to implicitly declare
801 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
802 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
803 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity()))
804 DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
807 // Implicitly declare member functions with the name we're looking for, if in
808 // fact we are in a scope where it matters.
810 Scope *Initial = S;
811 IdentifierResolver::iterator
812 I = IdResolver.begin(Name),
813 IEnd = IdResolver.end();
815 // First we lookup local scope.
816 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
817 // ...During unqualified name lookup (3.4.1), the names appear as if
818 // they were declared in the nearest enclosing namespace which contains
819 // both the using-directive and the nominated namespace.
820 // [Note: in this context, "contains" means "contains directly or
821 // indirectly".
823 // For example:
824 // namespace A { int i; }
825 // void foo() {
826 // int i;
827 // {
828 // using namespace A;
829 // ++i; // finds local 'i', A::i appears at global scope
830 // }
831 // }
833 DeclContext *OutsideOfTemplateParamDC = 0;
834 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
835 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
837 // Check whether the IdResolver has anything in this scope.
838 bool Found = false;
839 for (; I != IEnd && S->isDeclScope(*I); ++I) {
840 if (R.isAcceptableDecl(*I)) {
841 Found = true;
842 R.addDecl(*I);
845 if (Found) {
846 R.resolveKind();
847 if (S->isClassScope())
848 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
849 R.setNamingClass(Record);
850 return true;
853 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
854 S->getParent() && !S->getParent()->isTemplateParamScope()) {
855 // We've just searched the last template parameter scope and
856 // found nothing, so look into the the contexts between the
857 // lexical and semantic declaration contexts returned by
858 // findOuterContext(). This implements the name lookup behavior
859 // of C++ [temp.local]p8.
860 Ctx = OutsideOfTemplateParamDC;
861 OutsideOfTemplateParamDC = 0;
864 if (Ctx) {
865 DeclContext *OuterCtx;
866 bool SearchAfterTemplateScope;
867 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
868 if (SearchAfterTemplateScope)
869 OutsideOfTemplateParamDC = OuterCtx;
871 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
872 // We do not directly look into transparent contexts, since
873 // those entities will be found in the nearest enclosing
874 // non-transparent context.
875 if (Ctx->isTransparentContext())
876 continue;
878 // We do not look directly into function or method contexts,
879 // since all of the local variables and parameters of the
880 // function/method are present within the Scope.
881 if (Ctx->isFunctionOrMethod()) {
882 // If we have an Objective-C instance method, look for ivars
883 // in the corresponding interface.
884 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
885 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
886 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
887 ObjCInterfaceDecl *ClassDeclared;
888 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
889 Name.getAsIdentifierInfo(),
890 ClassDeclared)) {
891 if (R.isAcceptableDecl(Ivar)) {
892 R.addDecl(Ivar);
893 R.resolveKind();
894 return true;
900 continue;
903 // Perform qualified name lookup into this context.
904 // FIXME: In some cases, we know that every name that could be found by
905 // this qualified name lookup will also be on the identifier chain. For
906 // example, inside a class without any base classes, we never need to
907 // perform qualified lookup because all of the members are on top of the
908 // identifier chain.
909 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
910 return true;
915 // Stop if we ran out of scopes.
916 // FIXME: This really, really shouldn't be happening.
917 if (!S) return false;
919 // If we are looking for members, no need to look into global/namespace scope.
920 if (R.getLookupKind() == LookupMemberName)
921 return false;
923 // Collect UsingDirectiveDecls in all scopes, and recursively all
924 // nominated namespaces by those using-directives.
926 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
927 // don't build it for each lookup!
929 UnqualUsingDirectiveSet UDirs;
930 UDirs.visitScopeChain(Initial, S);
931 UDirs.done();
933 // Lookup namespace scope, and global scope.
934 // Unqualified name lookup in C++ requires looking into scopes
935 // that aren't strictly lexical, and therefore we walk through the
936 // context as well as walking through the scopes.
938 for (; S; S = S->getParent()) {
939 // Check whether the IdResolver has anything in this scope.
940 bool Found = false;
941 for (; I != IEnd && S->isDeclScope(*I); ++I) {
942 if (R.isAcceptableDecl(*I)) {
943 // We found something. Look for anything else in our scope
944 // with this same name and in an acceptable identifier
945 // namespace, so that we can construct an overload set if we
946 // need to.
947 Found = true;
948 R.addDecl(*I);
952 if (Found && S->isTemplateParamScope()) {
953 R.resolveKind();
954 return true;
957 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
958 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
959 S->getParent() && !S->getParent()->isTemplateParamScope()) {
960 // We've just searched the last template parameter scope and
961 // found nothing, so look into the the contexts between the
962 // lexical and semantic declaration contexts returned by
963 // findOuterContext(). This implements the name lookup behavior
964 // of C++ [temp.local]p8.
965 Ctx = OutsideOfTemplateParamDC;
966 OutsideOfTemplateParamDC = 0;
969 if (Ctx) {
970 DeclContext *OuterCtx;
971 bool SearchAfterTemplateScope;
972 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
973 if (SearchAfterTemplateScope)
974 OutsideOfTemplateParamDC = OuterCtx;
976 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
977 // We do not directly look into transparent contexts, since
978 // those entities will be found in the nearest enclosing
979 // non-transparent context.
980 if (Ctx->isTransparentContext())
981 continue;
983 // If we have a context, and it's not a context stashed in the
984 // template parameter scope for an out-of-line definition, also
985 // look into that context.
986 if (!(Found && S && S->isTemplateParamScope())) {
987 assert(Ctx->isFileContext() &&
988 "We should have been looking only at file context here already.");
990 // Look into context considering using-directives.
991 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
992 Found = true;
995 if (Found) {
996 R.resolveKind();
997 return true;
1000 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1001 return false;
1005 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1006 return false;
1009 return !R.empty();
1012 /// @brief Perform unqualified name lookup starting from a given
1013 /// scope.
1015 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1016 /// used to find names within the current scope. For example, 'x' in
1017 /// @code
1018 /// int x;
1019 /// int f() {
1020 /// return x; // unqualified name look finds 'x' in the global scope
1021 /// }
1022 /// @endcode
1024 /// Different lookup criteria can find different names. For example, a
1025 /// particular scope can have both a struct and a function of the same
1026 /// name, and each can be found by certain lookup criteria. For more
1027 /// information about lookup criteria, see the documentation for the
1028 /// class LookupCriteria.
1030 /// @param S The scope from which unqualified name lookup will
1031 /// begin. If the lookup criteria permits, name lookup may also search
1032 /// in the parent scopes.
1034 /// @param Name The name of the entity that we are searching for.
1036 /// @param Loc If provided, the source location where we're performing
1037 /// name lookup. At present, this is only used to produce diagnostics when
1038 /// C library functions (like "malloc") are implicitly declared.
1040 /// @returns The result of name lookup, which includes zero or more
1041 /// declarations and possibly additional information used to diagnose
1042 /// ambiguities.
1043 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1044 DeclarationName Name = R.getLookupName();
1045 if (!Name) return false;
1047 LookupNameKind NameKind = R.getLookupKind();
1049 if (!getLangOptions().CPlusPlus) {
1050 // Unqualified name lookup in C/Objective-C is purely lexical, so
1051 // search in the declarations attached to the name.
1053 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1054 // Find the nearest non-transparent declaration scope.
1055 while (!(S->getFlags() & Scope::DeclScope) ||
1056 (S->getEntity() &&
1057 static_cast<DeclContext *>(S->getEntity())
1058 ->isTransparentContext()))
1059 S = S->getParent();
1062 unsigned IDNS = R.getIdentifierNamespace();
1064 // Scan up the scope chain looking for a decl that matches this
1065 // identifier that is in the appropriate namespace. This search
1066 // should not take long, as shadowing of names is uncommon, and
1067 // deep shadowing is extremely uncommon.
1068 bool LeftStartingScope = false;
1070 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1071 IEnd = IdResolver.end();
1072 I != IEnd; ++I)
1073 if ((*I)->isInIdentifierNamespace(IDNS)) {
1074 if (NameKind == LookupRedeclarationWithLinkage) {
1075 // Determine whether this (or a previous) declaration is
1076 // out-of-scope.
1077 if (!LeftStartingScope && !S->isDeclScope(*I))
1078 LeftStartingScope = true;
1080 // If we found something outside of our starting scope that
1081 // does not have linkage, skip it.
1082 if (LeftStartingScope && !((*I)->hasLinkage()))
1083 continue;
1086 R.addDecl(*I);
1088 if ((*I)->getAttr<OverloadableAttr>()) {
1089 // If this declaration has the "overloadable" attribute, we
1090 // might have a set of overloaded functions.
1092 // Figure out what scope the identifier is in.
1093 while (!(S->getFlags() & Scope::DeclScope) ||
1094 !S->isDeclScope(*I))
1095 S = S->getParent();
1097 // Find the last declaration in this scope (with the same
1098 // name, naturally).
1099 IdentifierResolver::iterator LastI = I;
1100 for (++LastI; LastI != IEnd; ++LastI) {
1101 if (!S->isDeclScope(*LastI))
1102 break;
1103 R.addDecl(*LastI);
1107 R.resolveKind();
1109 return true;
1111 } else {
1112 // Perform C++ unqualified name lookup.
1113 if (CppLookupName(R, S))
1114 return true;
1117 // If we didn't find a use of this identifier, and if the identifier
1118 // corresponds to a compiler builtin, create the decl object for the builtin
1119 // now, injecting it into translation unit scope, and return it.
1120 if (AllowBuiltinCreation)
1121 return LookupBuiltin(*this, R);
1123 return false;
1126 /// @brief Perform qualified name lookup in the namespaces nominated by
1127 /// using directives by the given context.
1129 /// C++98 [namespace.qual]p2:
1130 /// Given X::m (where X is a user-declared namespace), or given ::m
1131 /// (where X is the global namespace), let S be the set of all
1132 /// declarations of m in X and in the transitive closure of all
1133 /// namespaces nominated by using-directives in X and its used
1134 /// namespaces, except that using-directives are ignored in any
1135 /// namespace, including X, directly containing one or more
1136 /// declarations of m. No namespace is searched more than once in
1137 /// the lookup of a name. If S is the empty set, the program is
1138 /// ill-formed. Otherwise, if S has exactly one member, or if the
1139 /// context of the reference is a using-declaration
1140 /// (namespace.udecl), S is the required set of declarations of
1141 /// m. Otherwise if the use of m is not one that allows a unique
1142 /// declaration to be chosen from S, the program is ill-formed.
1143 /// C++98 [namespace.qual]p5:
1144 /// During the lookup of a qualified namespace member name, if the
1145 /// lookup finds more than one declaration of the member, and if one
1146 /// declaration introduces a class name or enumeration name and the
1147 /// other declarations either introduce the same object, the same
1148 /// enumerator or a set of functions, the non-type name hides the
1149 /// class or enumeration name if and only if the declarations are
1150 /// from the same namespace; otherwise (the declarations are from
1151 /// different namespaces), the program is ill-formed.
1152 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1153 DeclContext *StartDC) {
1154 assert(StartDC->isFileContext() && "start context is not a file context");
1156 DeclContext::udir_iterator I = StartDC->using_directives_begin();
1157 DeclContext::udir_iterator E = StartDC->using_directives_end();
1159 if (I == E) return false;
1161 // We have at least added all these contexts to the queue.
1162 llvm::DenseSet<DeclContext*> Visited;
1163 Visited.insert(StartDC);
1165 // We have not yet looked into these namespaces, much less added
1166 // their "using-children" to the queue.
1167 llvm::SmallVector<NamespaceDecl*, 8> Queue;
1169 // We have already looked into the initial namespace; seed the queue
1170 // with its using-children.
1171 for (; I != E; ++I) {
1172 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace();
1173 if (Visited.insert(ND).second)
1174 Queue.push_back(ND);
1177 // The easiest way to implement the restriction in [namespace.qual]p5
1178 // is to check whether any of the individual results found a tag
1179 // and, if so, to declare an ambiguity if the final result is not
1180 // a tag.
1181 bool FoundTag = false;
1182 bool FoundNonTag = false;
1184 LookupResult LocalR(LookupResult::Temporary, R);
1186 bool Found = false;
1187 while (!Queue.empty()) {
1188 NamespaceDecl *ND = Queue.back();
1189 Queue.pop_back();
1191 // We go through some convolutions here to avoid copying results
1192 // between LookupResults.
1193 bool UseLocal = !R.empty();
1194 LookupResult &DirectR = UseLocal ? LocalR : R;
1195 bool FoundDirect = LookupDirect(S, DirectR, ND);
1197 if (FoundDirect) {
1198 // First do any local hiding.
1199 DirectR.resolveKind();
1201 // If the local result is a tag, remember that.
1202 if (DirectR.isSingleTagDecl())
1203 FoundTag = true;
1204 else
1205 FoundNonTag = true;
1207 // Append the local results to the total results if necessary.
1208 if (UseLocal) {
1209 R.addAllDecls(LocalR);
1210 LocalR.clear();
1214 // If we find names in this namespace, ignore its using directives.
1215 if (FoundDirect) {
1216 Found = true;
1217 continue;
1220 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) {
1221 NamespaceDecl *Nom = (*I)->getNominatedNamespace();
1222 if (Visited.insert(Nom).second)
1223 Queue.push_back(Nom);
1227 if (Found) {
1228 if (FoundTag && FoundNonTag)
1229 R.setAmbiguousQualifiedTagHiding();
1230 else
1231 R.resolveKind();
1234 return Found;
1237 /// \brief Callback that looks for any member of a class with the given name.
1238 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1239 CXXBasePath &Path,
1240 void *Name) {
1241 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1243 DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
1244 Path.Decls = BaseRecord->lookup(N);
1245 return Path.Decls.first != Path.Decls.second;
1248 /// \brief Determine whether the given set of member declarations contains only
1249 /// static members, nested types, and enumerators.
1250 template<typename InputIterator>
1251 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1252 Decl *D = (*First)->getUnderlyingDecl();
1253 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1254 return true;
1256 if (isa<CXXMethodDecl>(D)) {
1257 // Determine whether all of the methods are static.
1258 bool AllMethodsAreStatic = true;
1259 for(; First != Last; ++First) {
1260 D = (*First)->getUnderlyingDecl();
1262 if (!isa<CXXMethodDecl>(D)) {
1263 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
1264 break;
1267 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1268 AllMethodsAreStatic = false;
1269 break;
1273 if (AllMethodsAreStatic)
1274 return true;
1277 return false;
1280 /// \brief Perform qualified name lookup into a given context.
1282 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1283 /// names when the context of those names is explicit specified, e.g.,
1284 /// "std::vector" or "x->member", or as part of unqualified name lookup.
1286 /// Different lookup criteria can find different names. For example, a
1287 /// particular scope can have both a struct and a function of the same
1288 /// name, and each can be found by certain lookup criteria. For more
1289 /// information about lookup criteria, see the documentation for the
1290 /// class LookupCriteria.
1292 /// \param R captures both the lookup criteria and any lookup results found.
1294 /// \param LookupCtx The context in which qualified name lookup will
1295 /// search. If the lookup criteria permits, name lookup may also search
1296 /// in the parent contexts or (for C++ classes) base classes.
1298 /// \param InUnqualifiedLookup true if this is qualified name lookup that
1299 /// occurs as part of unqualified name lookup.
1301 /// \returns true if lookup succeeded, false if it failed.
1302 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
1303 bool InUnqualifiedLookup) {
1304 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
1306 if (!R.getLookupName())
1307 return false;
1309 // Make sure that the declaration context is complete.
1310 assert((!isa<TagDecl>(LookupCtx) ||
1311 LookupCtx->isDependentContext() ||
1312 cast<TagDecl>(LookupCtx)->isDefinition() ||
1313 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>()
1314 ->isBeingDefined()) &&
1315 "Declaration context must already be complete!");
1317 // Perform qualified name lookup into the LookupCtx.
1318 if (LookupDirect(*this, R, LookupCtx)) {
1319 R.resolveKind();
1320 if (isa<CXXRecordDecl>(LookupCtx))
1321 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
1322 return true;
1325 // Don't descend into implied contexts for redeclarations.
1326 // C++98 [namespace.qual]p6:
1327 // In a declaration for a namespace member in which the
1328 // declarator-id is a qualified-id, given that the qualified-id
1329 // for the namespace member has the form
1330 // nested-name-specifier unqualified-id
1331 // the unqualified-id shall name a member of the namespace
1332 // designated by the nested-name-specifier.
1333 // See also [class.mfct]p5 and [class.static.data]p2.
1334 if (R.isForRedeclaration())
1335 return false;
1337 // If this is a namespace, look it up in the implied namespaces.
1338 if (LookupCtx->isFileContext())
1339 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
1341 // If this isn't a C++ class, we aren't allowed to look into base
1342 // classes, we're done.
1343 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
1344 if (!LookupRec || !LookupRec->getDefinition())
1345 return false;
1347 // If we're performing qualified name lookup into a dependent class,
1348 // then we are actually looking into a current instantiation. If we have any
1349 // dependent base classes, then we either have to delay lookup until
1350 // template instantiation time (at which point all bases will be available)
1351 // or we have to fail.
1352 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
1353 LookupRec->hasAnyDependentBases()) {
1354 R.setNotFoundInCurrentInstantiation();
1355 return false;
1358 // Perform lookup into our base classes.
1359 CXXBasePaths Paths;
1360 Paths.setOrigin(LookupRec);
1362 // Look for this member in our base classes
1363 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0;
1364 switch (R.getLookupKind()) {
1365 case LookupOrdinaryName:
1366 case LookupMemberName:
1367 case LookupRedeclarationWithLinkage:
1368 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
1369 break;
1371 case LookupTagName:
1372 BaseCallback = &CXXRecordDecl::FindTagMember;
1373 break;
1375 case LookupAnyName:
1376 BaseCallback = &LookupAnyMember;
1377 break;
1379 case LookupUsingDeclName:
1380 // This lookup is for redeclarations only.
1382 case LookupOperatorName:
1383 case LookupNamespaceName:
1384 case LookupObjCProtocolName:
1385 // These lookups will never find a member in a C++ class (or base class).
1386 return false;
1388 case LookupNestedNameSpecifierName:
1389 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
1390 break;
1393 if (!LookupRec->lookupInBases(BaseCallback,
1394 R.getLookupName().getAsOpaquePtr(), Paths))
1395 return false;
1397 R.setNamingClass(LookupRec);
1399 // C++ [class.member.lookup]p2:
1400 // [...] If the resulting set of declarations are not all from
1401 // sub-objects of the same type, or the set has a nonstatic member
1402 // and includes members from distinct sub-objects, there is an
1403 // ambiguity and the program is ill-formed. Otherwise that set is
1404 // the result of the lookup.
1405 QualType SubobjectType;
1406 int SubobjectNumber = 0;
1407 AccessSpecifier SubobjectAccess = AS_none;
1409 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
1410 Path != PathEnd; ++Path) {
1411 const CXXBasePathElement &PathElement = Path->back();
1413 // Pick the best (i.e. most permissive i.e. numerically lowest) access
1414 // across all paths.
1415 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
1417 // Determine whether we're looking at a distinct sub-object or not.
1418 if (SubobjectType.isNull()) {
1419 // This is the first subobject we've looked at. Record its type.
1420 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1421 SubobjectNumber = PathElement.SubobjectNumber;
1422 continue;
1425 if (SubobjectType
1426 != Context.getCanonicalType(PathElement.Base->getType())) {
1427 // We found members of the given name in two subobjects of
1428 // different types. If the declaration sets aren't the same, this
1429 // this lookup is ambiguous.
1430 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second)) {
1431 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
1432 DeclContext::lookup_iterator FirstD = FirstPath->Decls.first;
1433 DeclContext::lookup_iterator CurrentD = Path->Decls.first;
1435 while (FirstD != FirstPath->Decls.second &&
1436 CurrentD != Path->Decls.second) {
1437 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
1438 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
1439 break;
1441 ++FirstD;
1442 ++CurrentD;
1445 if (FirstD == FirstPath->Decls.second &&
1446 CurrentD == Path->Decls.second)
1447 continue;
1450 R.setAmbiguousBaseSubobjectTypes(Paths);
1451 return true;
1454 if (SubobjectNumber != PathElement.SubobjectNumber) {
1455 // We have a different subobject of the same type.
1457 // C++ [class.member.lookup]p5:
1458 // A static member, a nested type or an enumerator defined in
1459 // a base class T can unambiguously be found even if an object
1460 // has more than one base class subobject of type T.
1461 if (HasOnlyStaticMembers(Path->Decls.first, Path->Decls.second))
1462 continue;
1464 // We have found a nonstatic member name in multiple, distinct
1465 // subobjects. Name lookup is ambiguous.
1466 R.setAmbiguousBaseSubobjects(Paths);
1467 return true;
1471 // Lookup in a base class succeeded; return these results.
1473 DeclContext::lookup_iterator I, E;
1474 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) {
1475 NamedDecl *D = *I;
1476 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
1477 D->getAccess());
1478 R.addDecl(D, AS);
1480 R.resolveKind();
1481 return true;
1484 /// @brief Performs name lookup for a name that was parsed in the
1485 /// source code, and may contain a C++ scope specifier.
1487 /// This routine is a convenience routine meant to be called from
1488 /// contexts that receive a name and an optional C++ scope specifier
1489 /// (e.g., "N::M::x"). It will then perform either qualified or
1490 /// unqualified name lookup (with LookupQualifiedName or LookupName,
1491 /// respectively) on the given name and return those results.
1493 /// @param S The scope from which unqualified name lookup will
1494 /// begin.
1496 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
1498 /// @param Name The name of the entity that name lookup will
1499 /// search for.
1501 /// @param Loc If provided, the source location where we're performing
1502 /// name lookup. At present, this is only used to produce diagnostics when
1503 /// C library functions (like "malloc") are implicitly declared.
1505 /// @param EnteringContext Indicates whether we are going to enter the
1506 /// context of the scope-specifier SS (if present).
1508 /// @returns True if any decls were found (but possibly ambiguous)
1509 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
1510 bool AllowBuiltinCreation, bool EnteringContext) {
1511 if (SS && SS->isInvalid()) {
1512 // When the scope specifier is invalid, don't even look for
1513 // anything.
1514 return false;
1517 if (SS && SS->isSet()) {
1518 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
1519 // We have resolved the scope specifier to a particular declaration
1520 // contex, and will perform name lookup in that context.
1521 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
1522 return false;
1524 R.setContextRange(SS->getRange());
1526 return LookupQualifiedName(R, DC);
1529 // We could not resolve the scope specified to a specific declaration
1530 // context, which means that SS refers to an unknown specialization.
1531 // Name lookup can't find anything in this case.
1532 return false;
1535 // Perform unqualified name lookup starting in the given scope.
1536 return LookupName(R, S, AllowBuiltinCreation);
1540 /// @brief Produce a diagnostic describing the ambiguity that resulted
1541 /// from name lookup.
1543 /// @param Result The ambiguous name lookup result.
1545 /// @param Name The name of the entity that name lookup was
1546 /// searching for.
1548 /// @param NameLoc The location of the name within the source code.
1550 /// @param LookupRange A source range that provides more
1551 /// source-location information concerning the lookup itself. For
1552 /// example, this range might highlight a nested-name-specifier that
1553 /// precedes the name.
1555 /// @returns true
1556 bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
1557 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1559 DeclarationName Name = Result.getLookupName();
1560 SourceLocation NameLoc = Result.getNameLoc();
1561 SourceRange LookupRange = Result.getContextRange();
1563 switch (Result.getAmbiguityKind()) {
1564 case LookupResult::AmbiguousBaseSubobjects: {
1565 CXXBasePaths *Paths = Result.getBasePaths();
1566 QualType SubobjectType = Paths->front().back().Base->getType();
1567 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1568 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1569 << LookupRange;
1571 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
1572 while (isa<CXXMethodDecl>(*Found) &&
1573 cast<CXXMethodDecl>(*Found)->isStatic())
1574 ++Found;
1576 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1578 return true;
1581 case LookupResult::AmbiguousBaseSubobjectTypes: {
1582 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1583 << Name << LookupRange;
1585 CXXBasePaths *Paths = Result.getBasePaths();
1586 std::set<Decl *> DeclsPrinted;
1587 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
1588 PathEnd = Paths->end();
1589 Path != PathEnd; ++Path) {
1590 Decl *D = *Path->Decls.first;
1591 if (DeclsPrinted.insert(D).second)
1592 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1595 return true;
1598 case LookupResult::AmbiguousTagHiding: {
1599 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
1601 llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
1603 LookupResult::iterator DI, DE = Result.end();
1604 for (DI = Result.begin(); DI != DE; ++DI)
1605 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) {
1606 TagDecls.insert(TD);
1607 Diag(TD->getLocation(), diag::note_hidden_tag);
1610 for (DI = Result.begin(); DI != DE; ++DI)
1611 if (!isa<TagDecl>(*DI))
1612 Diag((*DI)->getLocation(), diag::note_hiding_object);
1614 // For recovery purposes, go ahead and implement the hiding.
1615 LookupResult::Filter F = Result.makeFilter();
1616 while (F.hasNext()) {
1617 if (TagDecls.count(F.next()))
1618 F.erase();
1620 F.done();
1622 return true;
1625 case LookupResult::AmbiguousReference: {
1626 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1628 LookupResult::iterator DI = Result.begin(), DE = Result.end();
1629 for (; DI != DE; ++DI)
1630 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
1632 return true;
1636 llvm_unreachable("unknown ambiguity kind");
1637 return true;
1640 namespace {
1641 struct AssociatedLookup {
1642 AssociatedLookup(Sema &S,
1643 Sema::AssociatedNamespaceSet &Namespaces,
1644 Sema::AssociatedClassSet &Classes)
1645 : S(S), Namespaces(Namespaces), Classes(Classes) {
1648 Sema &S;
1649 Sema::AssociatedNamespaceSet &Namespaces;
1650 Sema::AssociatedClassSet &Classes;
1654 static void
1655 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
1657 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
1658 DeclContext *Ctx) {
1659 // Add the associated namespace for this class.
1661 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
1662 // be a locally scoped record.
1664 // We skip out of inline namespaces. The innermost non-inline namespace
1665 // contains all names of all its nested inline namespaces anyway, so we can
1666 // replace the entire inline namespace tree with its root.
1667 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
1668 Ctx->isInlineNamespace())
1669 Ctx = Ctx->getParent();
1671 if (Ctx->isFileContext())
1672 Namespaces.insert(Ctx->getPrimaryContext());
1675 // \brief Add the associated classes and namespaces for argument-dependent
1676 // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
1677 static void
1678 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1679 const TemplateArgument &Arg) {
1680 // C++ [basic.lookup.koenig]p2, last bullet:
1681 // -- [...] ;
1682 switch (Arg.getKind()) {
1683 case TemplateArgument::Null:
1684 break;
1686 case TemplateArgument::Type:
1687 // [...] the namespaces and classes associated with the types of the
1688 // template arguments provided for template type parameters (excluding
1689 // template template parameters)
1690 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
1691 break;
1693 case TemplateArgument::Template: {
1694 // [...] the namespaces in which any template template arguments are
1695 // defined; and the classes in which any member templates used as
1696 // template template arguments are defined.
1697 TemplateName Template = Arg.getAsTemplate();
1698 if (ClassTemplateDecl *ClassTemplate
1699 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
1700 DeclContext *Ctx = ClassTemplate->getDeclContext();
1701 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1702 Result.Classes.insert(EnclosingClass);
1703 // Add the associated namespace for this class.
1704 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1706 break;
1709 case TemplateArgument::Declaration:
1710 case TemplateArgument::Integral:
1711 case TemplateArgument::Expression:
1712 // [Note: non-type template arguments do not contribute to the set of
1713 // associated namespaces. ]
1714 break;
1716 case TemplateArgument::Pack:
1717 for (TemplateArgument::pack_iterator P = Arg.pack_begin(),
1718 PEnd = Arg.pack_end();
1719 P != PEnd; ++P)
1720 addAssociatedClassesAndNamespaces(Result, *P);
1721 break;
1725 // \brief Add the associated classes and namespaces for
1726 // argument-dependent lookup with an argument of class type
1727 // (C++ [basic.lookup.koenig]p2).
1728 static void
1729 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
1730 CXXRecordDecl *Class) {
1732 // Just silently ignore anything whose name is __va_list_tag.
1733 if (Class->getDeclName() == Result.S.VAListTagName)
1734 return;
1736 // C++ [basic.lookup.koenig]p2:
1737 // [...]
1738 // -- If T is a class type (including unions), its associated
1739 // classes are: the class itself; the class of which it is a
1740 // member, if any; and its direct and indirect base
1741 // classes. Its associated namespaces are the namespaces in
1742 // which its associated classes are defined.
1744 // Add the class of which it is a member, if any.
1745 DeclContext *Ctx = Class->getDeclContext();
1746 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1747 Result.Classes.insert(EnclosingClass);
1748 // Add the associated namespace for this class.
1749 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1751 // Add the class itself. If we've already seen this class, we don't
1752 // need to visit base classes.
1753 if (!Result.Classes.insert(Class))
1754 return;
1756 // -- If T is a template-id, its associated namespaces and classes are
1757 // the namespace in which the template is defined; for member
1758 // templates, the member template’s class; the namespaces and classes
1759 // associated with the types of the template arguments provided for
1760 // template type parameters (excluding template template parameters); the
1761 // namespaces in which any template template arguments are defined; and
1762 // the classes in which any member templates used as template template
1763 // arguments are defined. [Note: non-type template arguments do not
1764 // contribute to the set of associated namespaces. ]
1765 if (ClassTemplateSpecializationDecl *Spec
1766 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
1767 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
1768 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1769 Result.Classes.insert(EnclosingClass);
1770 // Add the associated namespace for this class.
1771 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1773 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1774 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
1775 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
1778 // Only recurse into base classes for complete types.
1779 if (!Class->hasDefinition()) {
1780 // FIXME: we might need to instantiate templates here
1781 return;
1784 // Add direct and indirect base classes along with their associated
1785 // namespaces.
1786 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1787 Bases.push_back(Class);
1788 while (!Bases.empty()) {
1789 // Pop this class off the stack.
1790 Class = Bases.back();
1791 Bases.pop_back();
1793 // Visit the base classes.
1794 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1795 BaseEnd = Class->bases_end();
1796 Base != BaseEnd; ++Base) {
1797 const RecordType *BaseType = Base->getType()->getAs<RecordType>();
1798 // In dependent contexts, we do ADL twice, and the first time around,
1799 // the base type might be a dependent TemplateSpecializationType, or a
1800 // TemplateTypeParmType. If that happens, simply ignore it.
1801 // FIXME: If we want to support export, we probably need to add the
1802 // namespace of the template in a TemplateSpecializationType, or even
1803 // the classes and namespaces of known non-dependent arguments.
1804 if (!BaseType)
1805 continue;
1806 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1807 if (Result.Classes.insert(BaseDecl)) {
1808 // Find the associated namespace for this base class.
1809 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1810 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
1812 // Make sure we visit the bases of this base class.
1813 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1814 Bases.push_back(BaseDecl);
1820 // \brief Add the associated classes and namespaces for
1821 // argument-dependent lookup with an argument of type T
1822 // (C++ [basic.lookup.koenig]p2).
1823 static void
1824 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
1825 // C++ [basic.lookup.koenig]p2:
1827 // For each argument type T in the function call, there is a set
1828 // of zero or more associated namespaces and a set of zero or more
1829 // associated classes to be considered. The sets of namespaces and
1830 // classes is determined entirely by the types of the function
1831 // arguments (and the namespace of any template template
1832 // argument). Typedef names and using-declarations used to specify
1833 // the types do not contribute to this set. The sets of namespaces
1834 // and classes are determined in the following way:
1836 llvm::SmallVector<const Type *, 16> Queue;
1837 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
1839 while (true) {
1840 switch (T->getTypeClass()) {
1842 #define TYPE(Class, Base)
1843 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1844 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1845 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
1846 #define ABSTRACT_TYPE(Class, Base)
1847 #include "clang/AST/TypeNodes.def"
1848 // T is canonical. We can also ignore dependent types because
1849 // we don't need to do ADL at the definition point, but if we
1850 // wanted to implement template export (or if we find some other
1851 // use for associated classes and namespaces...) this would be
1852 // wrong.
1853 break;
1855 // -- If T is a pointer to U or an array of U, its associated
1856 // namespaces and classes are those associated with U.
1857 case Type::Pointer:
1858 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
1859 continue;
1860 case Type::ConstantArray:
1861 case Type::IncompleteArray:
1862 case Type::VariableArray:
1863 T = cast<ArrayType>(T)->getElementType().getTypePtr();
1864 continue;
1866 // -- If T is a fundamental type, its associated sets of
1867 // namespaces and classes are both empty.
1868 case Type::Builtin:
1869 break;
1871 // -- If T is a class type (including unions), its associated
1872 // classes are: the class itself; the class of which it is a
1873 // member, if any; and its direct and indirect base
1874 // classes. Its associated namespaces are the namespaces in
1875 // which its associated classes are defined.
1876 case Type::Record: {
1877 CXXRecordDecl *Class
1878 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
1879 addAssociatedClassesAndNamespaces(Result, Class);
1880 break;
1883 // -- If T is an enumeration type, its associated namespace is
1884 // the namespace in which it is defined. If it is class
1885 // member, its associated class is the member’s class; else
1886 // it has no associated class.
1887 case Type::Enum: {
1888 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
1890 DeclContext *Ctx = Enum->getDeclContext();
1891 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1892 Result.Classes.insert(EnclosingClass);
1894 // Add the associated namespace for this class.
1895 CollectEnclosingNamespace(Result.Namespaces, Ctx);
1897 break;
1900 // -- If T is a function type, its associated namespaces and
1901 // classes are those associated with the function parameter
1902 // types and those associated with the return type.
1903 case Type::FunctionProto: {
1904 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1905 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1906 ArgEnd = Proto->arg_type_end();
1907 Arg != ArgEnd; ++Arg)
1908 Queue.push_back(Arg->getTypePtr());
1909 // fallthrough
1911 case Type::FunctionNoProto: {
1912 const FunctionType *FnType = cast<FunctionType>(T);
1913 T = FnType->getResultType().getTypePtr();
1914 continue;
1917 // -- If T is a pointer to a member function of a class X, its
1918 // associated namespaces and classes are those associated
1919 // with the function parameter types and return type,
1920 // together with those associated with X.
1922 // -- If T is a pointer to a data member of class X, its
1923 // associated namespaces and classes are those associated
1924 // with the member type together with those associated with
1925 // X.
1926 case Type::MemberPointer: {
1927 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
1929 // Queue up the class type into which this points.
1930 Queue.push_back(MemberPtr->getClass());
1932 // And directly continue with the pointee type.
1933 T = MemberPtr->getPointeeType().getTypePtr();
1934 continue;
1937 // As an extension, treat this like a normal pointer.
1938 case Type::BlockPointer:
1939 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
1940 continue;
1942 // References aren't covered by the standard, but that's such an
1943 // obvious defect that we cover them anyway.
1944 case Type::LValueReference:
1945 case Type::RValueReference:
1946 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
1947 continue;
1949 // These are fundamental types.
1950 case Type::Vector:
1951 case Type::ExtVector:
1952 case Type::Complex:
1953 break;
1955 // These are ignored by ADL.
1956 case Type::ObjCObject:
1957 case Type::ObjCInterface:
1958 case Type::ObjCObjectPointer:
1959 break;
1962 if (Queue.empty()) break;
1963 T = Queue.back();
1964 Queue.pop_back();
1968 /// \brief Find the associated classes and namespaces for
1969 /// argument-dependent lookup for a call with the given set of
1970 /// arguments.
1972 /// This routine computes the sets of associated classes and associated
1973 /// namespaces searched by argument-dependent lookup
1974 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
1975 void
1976 Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1977 AssociatedNamespaceSet &AssociatedNamespaces,
1978 AssociatedClassSet &AssociatedClasses) {
1979 AssociatedNamespaces.clear();
1980 AssociatedClasses.clear();
1982 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses);
1984 // C++ [basic.lookup.koenig]p2:
1985 // For each argument type T in the function call, there is a set
1986 // of zero or more associated namespaces and a set of zero or more
1987 // associated classes to be considered. The sets of namespaces and
1988 // classes is determined entirely by the types of the function
1989 // arguments (and the namespace of any template template
1990 // argument).
1991 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1992 Expr *Arg = Args[ArgIdx];
1994 if (Arg->getType() != Context.OverloadTy) {
1995 addAssociatedClassesAndNamespaces(Result, Arg->getType());
1996 continue;
1999 // [...] In addition, if the argument is the name or address of a
2000 // set of overloaded functions and/or function templates, its
2001 // associated classes and namespaces are the union of those
2002 // associated with each of the members of the set: the namespace
2003 // in which the function or function template is defined and the
2004 // classes and namespaces associated with its (non-dependent)
2005 // parameter types and return type.
2006 Arg = Arg->IgnoreParens();
2007 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2008 if (unaryOp->getOpcode() == UO_AddrOf)
2009 Arg = unaryOp->getSubExpr();
2011 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2012 if (!ULE) continue;
2014 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end();
2015 I != E; ++I) {
2016 // Look through any using declarations to find the underlying function.
2017 NamedDecl *Fn = (*I)->getUnderlyingDecl();
2019 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn);
2020 if (!FDecl)
2021 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl();
2023 // Add the classes and namespaces associated with the parameter
2024 // types and return type of this function.
2025 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2030 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
2031 /// an acceptable non-member overloaded operator for a call whose
2032 /// arguments have types T1 (and, if non-empty, T2). This routine
2033 /// implements the check in C++ [over.match.oper]p3b2 concerning
2034 /// enumeration types.
2035 static bool
2036 IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
2037 QualType T1, QualType T2,
2038 ASTContext &Context) {
2039 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
2040 return true;
2042 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
2043 return true;
2045 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
2046 if (Proto->getNumArgs() < 1)
2047 return false;
2049 if (T1->isEnumeralType()) {
2050 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
2051 if (Context.hasSameUnqualifiedType(T1, ArgType))
2052 return true;
2055 if (Proto->getNumArgs() < 2)
2056 return false;
2058 if (!T2.isNull() && T2->isEnumeralType()) {
2059 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
2060 if (Context.hasSameUnqualifiedType(T2, ArgType))
2061 return true;
2064 return false;
2067 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2068 SourceLocation Loc,
2069 LookupNameKind NameKind,
2070 RedeclarationKind Redecl) {
2071 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2072 LookupName(R, S);
2073 return R.getAsSingle<NamedDecl>();
2076 /// \brief Find the protocol with the given name, if any.
2077 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2078 SourceLocation IdLoc) {
2079 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2080 LookupObjCProtocolName);
2081 return cast_or_null<ObjCProtocolDecl>(D);
2084 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2085 QualType T1, QualType T2,
2086 UnresolvedSetImpl &Functions) {
2087 // C++ [over.match.oper]p3:
2088 // -- The set of non-member candidates is the result of the
2089 // unqualified lookup of operator@ in the context of the
2090 // expression according to the usual rules for name lookup in
2091 // unqualified function calls (3.4.2) except that all member
2092 // functions are ignored. However, if no operand has a class
2093 // type, only those non-member functions in the lookup set
2094 // that have a first parameter of type T1 or "reference to
2095 // (possibly cv-qualified) T1", when T1 is an enumeration
2096 // type, or (if there is a right operand) a second parameter
2097 // of type T2 or "reference to (possibly cv-qualified) T2",
2098 // when T2 is an enumeration type, are candidate functions.
2099 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2100 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2101 LookupName(Operators, S);
2103 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2105 if (Operators.empty())
2106 return;
2108 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
2109 Op != OpEnd; ++Op) {
2110 NamedDecl *Found = (*Op)->getUnderlyingDecl();
2111 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) {
2112 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
2113 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD
2114 } else if (FunctionTemplateDecl *FunTmpl
2115 = dyn_cast<FunctionTemplateDecl>(Found)) {
2116 // FIXME: friend operators?
2117 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate,
2118 // later?
2119 if (!FunTmpl->getDeclContext()->isRecord())
2120 Functions.addDecl(*Op, Op.getAccess());
2125 /// \brief Look up the constructors for the given class.
2126 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
2127 // If the copy constructor has not yet been declared, do so now.
2128 if (CanDeclareSpecialMemberFunction(Context, Class)) {
2129 if (!Class->hasDeclaredDefaultConstructor())
2130 DeclareImplicitDefaultConstructor(Class);
2131 if (!Class->hasDeclaredCopyConstructor())
2132 DeclareImplicitCopyConstructor(Class);
2135 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
2136 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
2137 return Class->lookup(Name);
2140 /// \brief Look for the destructor of the given class.
2142 /// During semantic analysis, this routine should be used in lieu of
2143 /// CXXRecordDecl::getDestructor().
2145 /// \returns The destructor for this class.
2146 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
2147 // If the destructor has not yet been declared, do so now.
2148 if (CanDeclareSpecialMemberFunction(Context, Class) &&
2149 !Class->hasDeclaredDestructor())
2150 DeclareImplicitDestructor(Class);
2152 return Class->getDestructor();
2155 void ADLResult::insert(NamedDecl *New) {
2156 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
2158 // If we haven't yet seen a decl for this key, or the last decl
2159 // was exactly this one, we're done.
2160 if (Old == 0 || Old == New) {
2161 Old = New;
2162 return;
2165 // Otherwise, decide which is a more recent redeclaration.
2166 FunctionDecl *OldFD, *NewFD;
2167 if (isa<FunctionTemplateDecl>(New)) {
2168 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl();
2169 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl();
2170 } else {
2171 OldFD = cast<FunctionDecl>(Old);
2172 NewFD = cast<FunctionDecl>(New);
2175 FunctionDecl *Cursor = NewFD;
2176 while (true) {
2177 Cursor = Cursor->getPreviousDeclaration();
2179 // If we got to the end without finding OldFD, OldFD is the newer
2180 // declaration; leave things as they are.
2181 if (!Cursor) return;
2183 // If we do find OldFD, then NewFD is newer.
2184 if (Cursor == OldFD) break;
2186 // Otherwise, keep looking.
2189 Old = New;
2192 void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator,
2193 Expr **Args, unsigned NumArgs,
2194 ADLResult &Result) {
2195 // Find all of the associated namespaces and classes based on the
2196 // arguments we have.
2197 AssociatedNamespaceSet AssociatedNamespaces;
2198 AssociatedClassSet AssociatedClasses;
2199 FindAssociatedClassesAndNamespaces(Args, NumArgs,
2200 AssociatedNamespaces,
2201 AssociatedClasses);
2203 QualType T1, T2;
2204 if (Operator) {
2205 T1 = Args[0]->getType();
2206 if (NumArgs >= 2)
2207 T2 = Args[1]->getType();
2210 // C++ [basic.lookup.argdep]p3:
2211 // Let X be the lookup set produced by unqualified lookup (3.4.1)
2212 // and let Y be the lookup set produced by argument dependent
2213 // lookup (defined as follows). If X contains [...] then Y is
2214 // empty. Otherwise Y is the set of declarations found in the
2215 // namespaces associated with the argument types as described
2216 // below. The set of declarations found by the lookup of the name
2217 // is the union of X and Y.
2219 // Here, we compute Y and add its members to the overloaded
2220 // candidate set.
2221 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
2222 NSEnd = AssociatedNamespaces.end();
2223 NS != NSEnd; ++NS) {
2224 // When considering an associated namespace, the lookup is the
2225 // same as the lookup performed when the associated namespace is
2226 // used as a qualifier (3.4.3.2) except that:
2228 // -- Any using-directives in the associated namespace are
2229 // ignored.
2231 // -- Any namespace-scope friend functions declared in
2232 // associated classes are visible within their respective
2233 // namespaces even if they are not visible during an ordinary
2234 // lookup (11.4).
2235 DeclContext::lookup_iterator I, E;
2236 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
2237 NamedDecl *D = *I;
2238 // If the only declaration here is an ordinary friend, consider
2239 // it only if it was declared in an associated classes.
2240 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
2241 DeclContext *LexDC = D->getLexicalDeclContext();
2242 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)))
2243 continue;
2246 if (isa<UsingShadowDecl>(D))
2247 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2249 if (isa<FunctionDecl>(D)) {
2250 if (Operator &&
2251 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D),
2252 T1, T2, Context))
2253 continue;
2254 } else if (!isa<FunctionTemplateDecl>(D))
2255 continue;
2257 Result.insert(D);
2262 //----------------------------------------------------------------------------
2263 // Search for all visible declarations.
2264 //----------------------------------------------------------------------------
2265 VisibleDeclConsumer::~VisibleDeclConsumer() { }
2267 namespace {
2269 class ShadowContextRAII;
2271 class VisibleDeclsRecord {
2272 public:
2273 /// \brief An entry in the shadow map, which is optimized to store a
2274 /// single declaration (the common case) but can also store a list
2275 /// of declarations.
2276 class ShadowMapEntry {
2277 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector;
2279 /// \brief Contains either the solitary NamedDecl * or a vector
2280 /// of declarations.
2281 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector;
2283 public:
2284 ShadowMapEntry() : DeclOrVector() { }
2286 void Add(NamedDecl *ND);
2287 void Destroy();
2289 // Iteration.
2290 typedef NamedDecl **iterator;
2291 iterator begin();
2292 iterator end();
2295 private:
2296 /// \brief A mapping from declaration names to the declarations that have
2297 /// this name within a particular scope.
2298 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
2300 /// \brief A list of shadow maps, which is used to model name hiding.
2301 std::list<ShadowMap> ShadowMaps;
2303 /// \brief The declaration contexts we have already visited.
2304 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
2306 friend class ShadowContextRAII;
2308 public:
2309 /// \brief Determine whether we have already visited this context
2310 /// (and, if not, note that we are going to visit that context now).
2311 bool visitedContext(DeclContext *Ctx) {
2312 return !VisitedContexts.insert(Ctx);
2315 bool alreadyVisitedContext(DeclContext *Ctx) {
2316 return VisitedContexts.count(Ctx);
2319 /// \brief Determine whether the given declaration is hidden in the
2320 /// current scope.
2322 /// \returns the declaration that hides the given declaration, or
2323 /// NULL if no such declaration exists.
2324 NamedDecl *checkHidden(NamedDecl *ND);
2326 /// \brief Add a declaration to the current shadow map.
2327 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); }
2330 /// \brief RAII object that records when we've entered a shadow context.
2331 class ShadowContextRAII {
2332 VisibleDeclsRecord &Visible;
2334 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
2336 public:
2337 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
2338 Visible.ShadowMaps.push_back(ShadowMap());
2341 ~ShadowContextRAII() {
2342 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(),
2343 EEnd = Visible.ShadowMaps.back().end();
2344 E != EEnd;
2345 ++E)
2346 E->second.Destroy();
2348 Visible.ShadowMaps.pop_back();
2352 } // end anonymous namespace
2354 void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) {
2355 if (DeclOrVector.isNull()) {
2356 // 0 - > 1 elements: just set the single element information.
2357 DeclOrVector = ND;
2358 return;
2361 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
2362 // 1 -> 2 elements: create the vector of results and push in the
2363 // existing declaration.
2364 DeclVector *Vec = new DeclVector;
2365 Vec->push_back(PrevND);
2366 DeclOrVector = Vec;
2369 // Add the new element to the end of the vector.
2370 DeclOrVector.get<DeclVector*>()->push_back(ND);
2373 void VisibleDeclsRecord::ShadowMapEntry::Destroy() {
2374 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) {
2375 delete Vec;
2376 DeclOrVector = ((NamedDecl *)0);
2380 VisibleDeclsRecord::ShadowMapEntry::iterator
2381 VisibleDeclsRecord::ShadowMapEntry::begin() {
2382 if (DeclOrVector.isNull())
2383 return 0;
2385 if (DeclOrVector.dyn_cast<NamedDecl *>())
2386 return &reinterpret_cast<NamedDecl*&>(DeclOrVector);
2388 return DeclOrVector.get<DeclVector *>()->begin();
2391 VisibleDeclsRecord::ShadowMapEntry::iterator
2392 VisibleDeclsRecord::ShadowMapEntry::end() {
2393 if (DeclOrVector.isNull())
2394 return 0;
2396 if (DeclOrVector.dyn_cast<NamedDecl *>())
2397 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1;
2399 return DeclOrVector.get<DeclVector *>()->end();
2402 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
2403 // Look through using declarations.
2404 ND = ND->getUnderlyingDecl();
2406 unsigned IDNS = ND->getIdentifierNamespace();
2407 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
2408 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
2409 SM != SMEnd; ++SM) {
2410 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
2411 if (Pos == SM->end())
2412 continue;
2414 for (ShadowMapEntry::iterator I = Pos->second.begin(),
2415 IEnd = Pos->second.end();
2416 I != IEnd; ++I) {
2417 // A tag declaration does not hide a non-tag declaration.
2418 if ((*I)->hasTagIdentifierNamespace() &&
2419 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
2420 Decl::IDNS_ObjCProtocol)))
2421 continue;
2423 // Protocols are in distinct namespaces from everything else.
2424 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
2425 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
2426 (*I)->getIdentifierNamespace() != IDNS)
2427 continue;
2429 // Functions and function templates in the same scope overload
2430 // rather than hide. FIXME: Look for hiding based on function
2431 // signatures!
2432 if ((*I)->isFunctionOrFunctionTemplate() &&
2433 ND->isFunctionOrFunctionTemplate() &&
2434 SM == ShadowMaps.rbegin())
2435 continue;
2437 // We've found a declaration that hides this one.
2438 return *I;
2442 return 0;
2445 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
2446 bool QualifiedNameLookup,
2447 bool InBaseClass,
2448 VisibleDeclConsumer &Consumer,
2449 VisibleDeclsRecord &Visited) {
2450 if (!Ctx)
2451 return;
2453 // Make sure we don't visit the same context twice.
2454 if (Visited.visitedContext(Ctx->getPrimaryContext()))
2455 return;
2457 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
2458 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
2460 // Enumerate all of the results in this context.
2461 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
2462 CurCtx = CurCtx->getNextContext()) {
2463 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
2464 DEnd = CurCtx->decls_end();
2465 D != DEnd; ++D) {
2466 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) {
2467 if (Result.isAcceptableDecl(ND)) {
2468 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass);
2469 Visited.add(ND);
2471 } else if (ObjCForwardProtocolDecl *ForwardProto
2472 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
2473 for (ObjCForwardProtocolDecl::protocol_iterator
2474 P = ForwardProto->protocol_begin(),
2475 PEnd = ForwardProto->protocol_end();
2476 P != PEnd;
2477 ++P) {
2478 if (Result.isAcceptableDecl(*P)) {
2479 Consumer.FoundDecl(*P, Visited.checkHidden(*P), InBaseClass);
2480 Visited.add(*P);
2484 // Visit transparent contexts and inline namespaces inside this context.
2485 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) {
2486 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
2487 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass,
2488 Consumer, Visited);
2493 // Traverse using directives for qualified name lookup.
2494 if (QualifiedNameLookup) {
2495 ShadowContextRAII Shadow(Visited);
2496 DeclContext::udir_iterator I, E;
2497 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) {
2498 LookupVisibleDecls((*I)->getNominatedNamespace(), Result,
2499 QualifiedNameLookup, InBaseClass, Consumer, Visited);
2503 // Traverse the contexts of inherited C++ classes.
2504 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
2505 if (!Record->hasDefinition())
2506 return;
2508 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
2509 BEnd = Record->bases_end();
2510 B != BEnd; ++B) {
2511 QualType BaseType = B->getType();
2513 // Don't look into dependent bases, because name lookup can't look
2514 // there anyway.
2515 if (BaseType->isDependentType())
2516 continue;
2518 const RecordType *Record = BaseType->getAs<RecordType>();
2519 if (!Record)
2520 continue;
2522 // FIXME: It would be nice to be able to determine whether referencing
2523 // a particular member would be ambiguous. For example, given
2525 // struct A { int member; };
2526 // struct B { int member; };
2527 // struct C : A, B { };
2529 // void f(C *c) { c->### }
2531 // accessing 'member' would result in an ambiguity. However, we
2532 // could be smart enough to qualify the member with the base
2533 // class, e.g.,
2535 // c->B::member
2537 // or
2539 // c->A::member
2541 // Find results in this base class (and its bases).
2542 ShadowContextRAII Shadow(Visited);
2543 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
2544 true, Consumer, Visited);
2548 // Traverse the contexts of Objective-C classes.
2549 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
2550 // Traverse categories.
2551 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2552 Category; Category = Category->getNextClassCategory()) {
2553 ShadowContextRAII Shadow(Visited);
2554 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false,
2555 Consumer, Visited);
2558 // Traverse protocols.
2559 for (ObjCInterfaceDecl::all_protocol_iterator
2560 I = IFace->all_referenced_protocol_begin(),
2561 E = IFace->all_referenced_protocol_end(); I != E; ++I) {
2562 ShadowContextRAII Shadow(Visited);
2563 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2564 Visited);
2567 // Traverse the superclass.
2568 if (IFace->getSuperClass()) {
2569 ShadowContextRAII Shadow(Visited);
2570 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
2571 true, Consumer, Visited);
2574 // If there is an implementation, traverse it. We do this to find
2575 // synthesized ivars.
2576 if (IFace->getImplementation()) {
2577 ShadowContextRAII Shadow(Visited);
2578 LookupVisibleDecls(IFace->getImplementation(), Result,
2579 QualifiedNameLookup, true, Consumer, Visited);
2581 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
2582 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(),
2583 E = Protocol->protocol_end(); I != E; ++I) {
2584 ShadowContextRAII Shadow(Visited);
2585 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2586 Visited);
2588 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
2589 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(),
2590 E = Category->protocol_end(); I != E; ++I) {
2591 ShadowContextRAII Shadow(Visited);
2592 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer,
2593 Visited);
2596 // If there is an implementation, traverse it.
2597 if (Category->getImplementation()) {
2598 ShadowContextRAII Shadow(Visited);
2599 LookupVisibleDecls(Category->getImplementation(), Result,
2600 QualifiedNameLookup, true, Consumer, Visited);
2605 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
2606 UnqualUsingDirectiveSet &UDirs,
2607 VisibleDeclConsumer &Consumer,
2608 VisibleDeclsRecord &Visited) {
2609 if (!S)
2610 return;
2612 if (!S->getEntity() ||
2613 (!S->getParent() &&
2614 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) ||
2615 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
2616 // Walk through the declarations in this Scope.
2617 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
2618 D != DEnd; ++D) {
2619 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
2620 if (Result.isAcceptableDecl(ND)) {
2621 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false);
2622 Visited.add(ND);
2627 // FIXME: C++ [temp.local]p8
2628 DeclContext *Entity = 0;
2629 if (S->getEntity()) {
2630 // Look into this scope's declaration context, along with any of its
2631 // parent lookup contexts (e.g., enclosing classes), up to the point
2632 // where we hit the context stored in the next outer scope.
2633 Entity = (DeclContext *)S->getEntity();
2634 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
2636 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
2637 Ctx = Ctx->getLookupParent()) {
2638 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
2639 if (Method->isInstanceMethod()) {
2640 // For instance methods, look for ivars in the method's interface.
2641 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
2642 Result.getNameLoc(), Sema::LookupMemberName);
2643 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
2644 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
2645 /*InBaseClass=*/false, Consumer, Visited);
2647 // Look for properties from which we can synthesize ivars, if
2648 // permitted.
2649 if (Result.getSema().getLangOptions().ObjCNonFragileABI2 &&
2650 IFace->getImplementation() &&
2651 Result.getLookupKind() == Sema::LookupOrdinaryName) {
2652 for (ObjCInterfaceDecl::prop_iterator
2653 P = IFace->prop_begin(),
2654 PEnd = IFace->prop_end();
2655 P != PEnd; ++P) {
2656 if (Result.getSema().canSynthesizeProvisionalIvar(*P) &&
2657 !IFace->lookupInstanceVariable((*P)->getIdentifier())) {
2658 Consumer.FoundDecl(*P, Visited.checkHidden(*P), false);
2659 Visited.add(*P);
2666 // We've already performed all of the name lookup that we need
2667 // to for Objective-C methods; the next context will be the
2668 // outer scope.
2669 break;
2672 if (Ctx->isFunctionOrMethod())
2673 continue;
2675 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
2676 /*InBaseClass=*/false, Consumer, Visited);
2678 } else if (!S->getParent()) {
2679 // Look into the translation unit scope. We walk through the translation
2680 // unit's declaration context, because the Scope itself won't have all of
2681 // the declarations if we loaded a precompiled header.
2682 // FIXME: We would like the translation unit's Scope object to point to the
2683 // translation unit, so we don't need this special "if" branch. However,
2684 // doing so would force the normal C++ name-lookup code to look into the
2685 // translation unit decl when the IdentifierInfo chains would suffice.
2686 // Once we fix that problem (which is part of a more general "don't look
2687 // in DeclContexts unless we have to" optimization), we can eliminate this.
2688 Entity = Result.getSema().Context.getTranslationUnitDecl();
2689 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
2690 /*InBaseClass=*/false, Consumer, Visited);
2693 if (Entity) {
2694 // Lookup visible declarations in any namespaces found by using
2695 // directives.
2696 UnqualUsingDirectiveSet::const_iterator UI, UEnd;
2697 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity);
2698 for (; UI != UEnd; ++UI)
2699 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()),
2700 Result, /*QualifiedNameLookup=*/false,
2701 /*InBaseClass=*/false, Consumer, Visited);
2704 // Lookup names in the parent scope.
2705 ShadowContextRAII Shadow(Visited);
2706 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
2709 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
2710 VisibleDeclConsumer &Consumer,
2711 bool IncludeGlobalScope) {
2712 // Determine the set of using directives available during
2713 // unqualified name lookup.
2714 Scope *Initial = S;
2715 UnqualUsingDirectiveSet UDirs;
2716 if (getLangOptions().CPlusPlus) {
2717 // Find the first namespace or translation-unit scope.
2718 while (S && !isNamespaceOrTranslationUnitScope(S))
2719 S = S->getParent();
2721 UDirs.visitScopeChain(Initial, S);
2723 UDirs.done();
2725 // Look for visible declarations.
2726 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2727 VisibleDeclsRecord Visited;
2728 if (!IncludeGlobalScope)
2729 Visited.visitedContext(Context.getTranslationUnitDecl());
2730 ShadowContextRAII Shadow(Visited);
2731 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
2734 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
2735 VisibleDeclConsumer &Consumer,
2736 bool IncludeGlobalScope) {
2737 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
2738 VisibleDeclsRecord Visited;
2739 if (!IncludeGlobalScope)
2740 Visited.visitedContext(Context.getTranslationUnitDecl());
2741 ShadowContextRAII Shadow(Visited);
2742 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
2743 /*InBaseClass=*/false, Consumer, Visited);
2746 //----------------------------------------------------------------------------
2747 // Typo correction
2748 //----------------------------------------------------------------------------
2750 namespace {
2751 class TypoCorrectionConsumer : public VisibleDeclConsumer {
2752 /// \brief The name written that is a typo in the source.
2753 llvm::StringRef Typo;
2755 /// \brief The results found that have the smallest edit distance
2756 /// found (so far) with the typo name.
2758 /// The boolean value indicates whether there is a keyword with this name.
2759 llvm::StringMap<bool, llvm::BumpPtrAllocator> BestResults;
2761 /// \brief The best edit distance found so far.
2762 unsigned BestEditDistance;
2764 public:
2765 explicit TypoCorrectionConsumer(IdentifierInfo *Typo)
2766 : Typo(Typo->getName()),
2767 BestEditDistance((std::numeric_limits<unsigned>::max)()) { }
2769 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass);
2770 void FoundName(llvm::StringRef Name);
2771 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword);
2773 typedef llvm::StringMap<bool, llvm::BumpPtrAllocator>::iterator iterator;
2774 iterator begin() { return BestResults.begin(); }
2775 iterator end() { return BestResults.end(); }
2776 void erase(iterator I) { BestResults.erase(I); }
2777 unsigned size() const { return BestResults.size(); }
2778 bool empty() const { return BestResults.empty(); }
2780 bool &operator[](llvm::StringRef Name) {
2781 return BestResults[Name];
2784 unsigned getBestEditDistance() const { return BestEditDistance; }
2789 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
2790 bool InBaseClass) {
2791 // Don't consider hidden names for typo correction.
2792 if (Hiding)
2793 return;
2795 // Only consider entities with identifiers for names, ignoring
2796 // special names (constructors, overloaded operators, selectors,
2797 // etc.).
2798 IdentifierInfo *Name = ND->getIdentifier();
2799 if (!Name)
2800 return;
2802 FoundName(Name->getName());
2805 void TypoCorrectionConsumer::FoundName(llvm::StringRef Name) {
2806 using namespace std;
2808 // Use a simple length-based heuristic to determine the minimum possible
2809 // edit distance. If the minimum isn't good enough, bail out early.
2810 unsigned MinED = abs((int)Name.size() - (int)Typo.size());
2811 if (MinED > BestEditDistance || (MinED && Typo.size() / MinED < 3))
2812 return;
2814 // Compute an upper bound on the allowable edit distance, so that the
2815 // edit-distance algorithm can short-circuit.
2816 unsigned UpperBound = min(unsigned((Typo.size() + 2) / 3), BestEditDistance);
2818 // Compute the edit distance between the typo and the name of this
2819 // entity. If this edit distance is not worse than the best edit
2820 // distance we've seen so far, add it to the list of results.
2821 unsigned ED = Typo.edit_distance(Name, true, UpperBound);
2822 if (ED == 0)
2823 return;
2825 if (ED < BestEditDistance) {
2826 // This result is better than any we've seen before; clear out
2827 // the previous results.
2828 BestResults.clear();
2829 BestEditDistance = ED;
2830 } else if (ED > BestEditDistance) {
2831 // This result is worse than the best results we've seen so far;
2832 // ignore it.
2833 return;
2836 // Add this name to the list of results. By not assigning a value, we
2837 // keep the current value if we've seen this name before (either as a
2838 // keyword or as a declaration), or get the default value (not a keyword)
2839 // if we haven't seen it before.
2840 (void)BestResults[Name];
2843 void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context,
2844 llvm::StringRef Keyword) {
2845 // Compute the edit distance between the typo and this keyword.
2846 // If this edit distance is not worse than the best edit
2847 // distance we've seen so far, add it to the list of results.
2848 unsigned ED = Typo.edit_distance(Keyword);
2849 if (ED < BestEditDistance) {
2850 BestResults.clear();
2851 BestEditDistance = ED;
2852 } else if (ED > BestEditDistance) {
2853 // This result is worse than the best results we've seen so far;
2854 // ignore it.
2855 return;
2858 BestResults[Keyword] = true;
2861 /// \brief Perform name lookup for a possible result for typo correction.
2862 static void LookupPotentialTypoResult(Sema &SemaRef,
2863 LookupResult &Res,
2864 IdentifierInfo *Name,
2865 Scope *S, CXXScopeSpec *SS,
2866 DeclContext *MemberContext,
2867 bool EnteringContext,
2868 Sema::CorrectTypoContext CTC) {
2869 Res.suppressDiagnostics();
2870 Res.clear();
2871 Res.setLookupName(Name);
2872 if (MemberContext) {
2873 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
2874 if (CTC == Sema::CTC_ObjCIvarLookup) {
2875 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
2876 Res.addDecl(Ivar);
2877 Res.resolveKind();
2878 return;
2882 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
2883 Res.addDecl(Prop);
2884 Res.resolveKind();
2885 return;
2889 SemaRef.LookupQualifiedName(Res, MemberContext);
2890 return;
2893 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
2894 EnteringContext);
2896 // Fake ivar lookup; this should really be part of
2897 // LookupParsedName.
2898 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2899 if (Method->isInstanceMethod() && Method->getClassInterface() &&
2900 (Res.empty() ||
2901 (Res.isSingleResult() &&
2902 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
2903 if (ObjCIvarDecl *IV
2904 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
2905 Res.addDecl(IV);
2906 Res.resolveKind();
2912 /// \brief Try to "correct" a typo in the source code by finding
2913 /// visible declarations whose names are similar to the name that was
2914 /// present in the source code.
2916 /// \param Res the \c LookupResult structure that contains the name
2917 /// that was present in the source code along with the name-lookup
2918 /// criteria used to search for the name. On success, this structure
2919 /// will contain the results of name lookup.
2921 /// \param S the scope in which name lookup occurs.
2923 /// \param SS the nested-name-specifier that precedes the name we're
2924 /// looking for, if present.
2926 /// \param MemberContext if non-NULL, the context in which to look for
2927 /// a member access expression.
2929 /// \param EnteringContext whether we're entering the context described by
2930 /// the nested-name-specifier SS.
2932 /// \param CTC The context in which typo correction occurs, which impacts the
2933 /// set of keywords permitted.
2935 /// \param OPT when non-NULL, the search for visible declarations will
2936 /// also walk the protocols in the qualified interfaces of \p OPT.
2938 /// \returns the corrected name if the typo was corrected, otherwise returns an
2939 /// empty \c DeclarationName. When a typo was corrected, the result structure
2940 /// may contain the results of name lookup for the correct name or it may be
2941 /// empty.
2942 DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS,
2943 DeclContext *MemberContext,
2944 bool EnteringContext,
2945 CorrectTypoContext CTC,
2946 const ObjCObjectPointerType *OPT) {
2947 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking)
2948 return DeclarationName();
2950 // We only attempt to correct typos for identifiers.
2951 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo();
2952 if (!Typo)
2953 return DeclarationName();
2955 // If the scope specifier itself was invalid, don't try to correct
2956 // typos.
2957 if (SS && SS->isInvalid())
2958 return DeclarationName();
2960 // Never try to correct typos during template deduction or
2961 // instantiation.
2962 if (!ActiveTemplateInstantiations.empty())
2963 return DeclarationName();
2965 TypoCorrectionConsumer Consumer(Typo);
2967 // Perform name lookup to find visible, similarly-named entities.
2968 bool IsUnqualifiedLookup = false;
2969 if (MemberContext) {
2970 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer);
2972 // Look in qualified interfaces.
2973 if (OPT) {
2974 for (ObjCObjectPointerType::qual_iterator
2975 I = OPT->qual_begin(), E = OPT->qual_end();
2976 I != E; ++I)
2977 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer);
2979 } else if (SS && SS->isSet()) {
2980 DeclContext *DC = computeDeclContext(*SS, EnteringContext);
2981 if (!DC)
2982 return DeclarationName();
2984 // Provide a stop gap for files that are just seriously broken. Trying
2985 // to correct all typos can turn into a HUGE performance penalty, causing
2986 // some files to take minutes to get rejected by the parser.
2987 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
2988 return DeclarationName();
2989 ++TyposCorrected;
2991 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer);
2992 } else {
2993 IsUnqualifiedLookup = true;
2994 UnqualifiedTyposCorrectedMap::iterator Cached
2995 = UnqualifiedTyposCorrected.find(Typo);
2996 if (Cached == UnqualifiedTyposCorrected.end()) {
2997 // Provide a stop gap for files that are just seriously broken. Trying
2998 // to correct all typos can turn into a HUGE performance penalty, causing
2999 // some files to take minutes to get rejected by the parser.
3000 if (TyposCorrected + UnqualifiedTyposCorrected.size() >= 20)
3001 return DeclarationName();
3003 // For unqualified lookup, look through all of the names that we have
3004 // seen in this translation unit.
3005 for (IdentifierTable::iterator I = Context.Idents.begin(),
3006 IEnd = Context.Idents.end();
3007 I != IEnd; ++I)
3008 Consumer.FoundName(I->getKey());
3010 // Walk through identifiers in external identifier sources.
3011 if (IdentifierInfoLookup *External
3012 = Context.Idents.getExternalIdentifierLookup()) {
3013 llvm::OwningPtr<IdentifierIterator> Iter(External->getIdentifiers());
3014 do {
3015 llvm::StringRef Name = Iter->Next();
3016 if (Name.empty())
3017 break;
3019 Consumer.FoundName(Name);
3020 } while (true);
3022 } else {
3023 // Use the cached value, unless it's a keyword. In the keyword case, we'll
3024 // end up adding the keyword below.
3025 if (Cached->second.first.empty())
3026 return DeclarationName();
3028 if (!Cached->second.second)
3029 Consumer.FoundName(Cached->second.first);
3033 // Add context-dependent keywords.
3034 bool WantTypeSpecifiers = false;
3035 bool WantExpressionKeywords = false;
3036 bool WantCXXNamedCasts = false;
3037 bool WantRemainingKeywords = false;
3038 switch (CTC) {
3039 case CTC_Unknown:
3040 WantTypeSpecifiers = true;
3041 WantExpressionKeywords = true;
3042 WantCXXNamedCasts = true;
3043 WantRemainingKeywords = true;
3045 if (ObjCMethodDecl *Method = getCurMethodDecl())
3046 if (Method->getClassInterface() &&
3047 Method->getClassInterface()->getSuperClass())
3048 Consumer.addKeywordResult(Context, "super");
3050 break;
3052 case CTC_NoKeywords:
3053 break;
3055 case CTC_Type:
3056 WantTypeSpecifiers = true;
3057 break;
3059 case CTC_ObjCMessageReceiver:
3060 Consumer.addKeywordResult(Context, "super");
3061 // Fall through to handle message receivers like expressions.
3063 case CTC_Expression:
3064 if (getLangOptions().CPlusPlus)
3065 WantTypeSpecifiers = true;
3066 WantExpressionKeywords = true;
3067 // Fall through to get C++ named casts.
3069 case CTC_CXXCasts:
3070 WantCXXNamedCasts = true;
3071 break;
3073 case CTC_ObjCPropertyLookup:
3074 // FIXME: Add "isa"?
3075 break;
3077 case CTC_MemberLookup:
3078 if (getLangOptions().CPlusPlus)
3079 Consumer.addKeywordResult(Context, "template");
3080 break;
3082 case CTC_ObjCIvarLookup:
3083 break;
3086 if (WantTypeSpecifiers) {
3087 // Add type-specifier keywords to the set of results.
3088 const char *CTypeSpecs[] = {
3089 "char", "const", "double", "enum", "float", "int", "long", "short",
3090 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool",
3091 "_Complex", "_Imaginary",
3092 // storage-specifiers as well
3093 "extern", "inline", "static", "typedef"
3096 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]);
3097 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
3098 Consumer.addKeywordResult(Context, CTypeSpecs[I]);
3100 if (getLangOptions().C99)
3101 Consumer.addKeywordResult(Context, "restrict");
3102 if (getLangOptions().Bool || getLangOptions().CPlusPlus)
3103 Consumer.addKeywordResult(Context, "bool");
3105 if (getLangOptions().CPlusPlus) {
3106 Consumer.addKeywordResult(Context, "class");
3107 Consumer.addKeywordResult(Context, "typename");
3108 Consumer.addKeywordResult(Context, "wchar_t");
3110 if (getLangOptions().CPlusPlus0x) {
3111 Consumer.addKeywordResult(Context, "char16_t");
3112 Consumer.addKeywordResult(Context, "char32_t");
3113 Consumer.addKeywordResult(Context, "constexpr");
3114 Consumer.addKeywordResult(Context, "decltype");
3115 Consumer.addKeywordResult(Context, "thread_local");
3119 if (getLangOptions().GNUMode)
3120 Consumer.addKeywordResult(Context, "typeof");
3123 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) {
3124 Consumer.addKeywordResult(Context, "const_cast");
3125 Consumer.addKeywordResult(Context, "dynamic_cast");
3126 Consumer.addKeywordResult(Context, "reinterpret_cast");
3127 Consumer.addKeywordResult(Context, "static_cast");
3130 if (WantExpressionKeywords) {
3131 Consumer.addKeywordResult(Context, "sizeof");
3132 if (getLangOptions().Bool || getLangOptions().CPlusPlus) {
3133 Consumer.addKeywordResult(Context, "false");
3134 Consumer.addKeywordResult(Context, "true");
3137 if (getLangOptions().CPlusPlus) {
3138 const char *CXXExprs[] = {
3139 "delete", "new", "operator", "throw", "typeid"
3141 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]);
3142 for (unsigned I = 0; I != NumCXXExprs; ++I)
3143 Consumer.addKeywordResult(Context, CXXExprs[I]);
3145 if (isa<CXXMethodDecl>(CurContext) &&
3146 cast<CXXMethodDecl>(CurContext)->isInstance())
3147 Consumer.addKeywordResult(Context, "this");
3149 if (getLangOptions().CPlusPlus0x) {
3150 Consumer.addKeywordResult(Context, "alignof");
3151 Consumer.addKeywordResult(Context, "nullptr");
3156 if (WantRemainingKeywords) {
3157 if (getCurFunctionOrMethodDecl() || getCurBlock()) {
3158 // Statements.
3159 const char *CStmts[] = {
3160 "do", "else", "for", "goto", "if", "return", "switch", "while" };
3161 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]);
3162 for (unsigned I = 0; I != NumCStmts; ++I)
3163 Consumer.addKeywordResult(Context, CStmts[I]);
3165 if (getLangOptions().CPlusPlus) {
3166 Consumer.addKeywordResult(Context, "catch");
3167 Consumer.addKeywordResult(Context, "try");
3170 if (S && S->getBreakParent())
3171 Consumer.addKeywordResult(Context, "break");
3173 if (S && S->getContinueParent())
3174 Consumer.addKeywordResult(Context, "continue");
3176 if (!getCurFunction()->SwitchStack.empty()) {
3177 Consumer.addKeywordResult(Context, "case");
3178 Consumer.addKeywordResult(Context, "default");
3180 } else {
3181 if (getLangOptions().CPlusPlus) {
3182 Consumer.addKeywordResult(Context, "namespace");
3183 Consumer.addKeywordResult(Context, "template");
3186 if (S && S->isClassScope()) {
3187 Consumer.addKeywordResult(Context, "explicit");
3188 Consumer.addKeywordResult(Context, "friend");
3189 Consumer.addKeywordResult(Context, "mutable");
3190 Consumer.addKeywordResult(Context, "private");
3191 Consumer.addKeywordResult(Context, "protected");
3192 Consumer.addKeywordResult(Context, "public");
3193 Consumer.addKeywordResult(Context, "virtual");
3197 if (getLangOptions().CPlusPlus) {
3198 Consumer.addKeywordResult(Context, "using");
3200 if (getLangOptions().CPlusPlus0x)
3201 Consumer.addKeywordResult(Context, "static_assert");
3205 // If we haven't found anything, we're done.
3206 if (Consumer.empty()) {
3207 // If this was an unqualified lookup, note that no correction was found.
3208 if (IsUnqualifiedLookup)
3209 (void)UnqualifiedTyposCorrected[Typo];
3211 return DeclarationName();
3214 // Make sure that the user typed at least 3 characters for each correction
3215 // made. Otherwise, we don't even both looking at the results.
3217 // We also suppress exact matches; those should be handled by a
3218 // different mechanism (e.g., one that introduces qualification in
3219 // C++).
3220 unsigned ED = Consumer.getBestEditDistance();
3221 if (ED > 0 && Typo->getName().size() / ED < 3) {
3222 // If this was an unqualified lookup, note that no correction was found.
3223 if (IsUnqualifiedLookup)
3224 (void)UnqualifiedTyposCorrected[Typo];
3226 return DeclarationName();
3229 // Weed out any names that could not be found by name lookup.
3230 bool LastLookupWasAccepted = false;
3231 for (TypoCorrectionConsumer::iterator I = Consumer.begin(),
3232 IEnd = Consumer.end();
3233 I != IEnd; /* Increment in loop. */) {
3234 // Keywords are always found.
3235 if (I->second) {
3236 ++I;
3237 continue;
3240 // Perform name lookup on this name.
3241 IdentifierInfo *Name = &Context.Idents.get(I->getKey());
3242 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3243 EnteringContext, CTC);
3245 switch (Res.getResultKind()) {
3246 case LookupResult::NotFound:
3247 case LookupResult::NotFoundInCurrentInstantiation:
3248 case LookupResult::Ambiguous:
3249 // We didn't find this name in our scope, or didn't like what we found;
3250 // ignore it.
3251 Res.suppressDiagnostics();
3253 TypoCorrectionConsumer::iterator Next = I;
3254 ++Next;
3255 Consumer.erase(I);
3256 I = Next;
3258 LastLookupWasAccepted = false;
3259 break;
3261 case LookupResult::Found:
3262 case LookupResult::FoundOverloaded:
3263 case LookupResult::FoundUnresolvedValue:
3264 ++I;
3265 LastLookupWasAccepted = true;
3266 break;
3269 if (Res.isAmbiguous()) {
3270 // We don't deal with ambiguities.
3271 Res.suppressDiagnostics();
3272 Res.clear();
3273 return DeclarationName();
3277 // If only a single name remains, return that result.
3278 if (Consumer.size() == 1) {
3279 IdentifierInfo *Name = &Context.Idents.get(Consumer.begin()->getKey());
3280 if (Consumer.begin()->second) {
3281 Res.suppressDiagnostics();
3282 Res.clear();
3284 // Don't correct to a keyword that's the same as the typo; the keyword
3285 // wasn't actually in scope.
3286 if (ED == 0) {
3287 Res.setLookupName(Typo);
3288 return DeclarationName();
3291 } else if (!LastLookupWasAccepted) {
3292 // Perform name lookup on this name.
3293 LookupPotentialTypoResult(*this, Res, Name, S, SS, MemberContext,
3294 EnteringContext, CTC);
3297 // Record the correction for unqualified lookup.
3298 if (IsUnqualifiedLookup)
3299 UnqualifiedTyposCorrected[Typo]
3300 = std::make_pair(Name->getName(), Consumer.begin()->second);
3302 return &Context.Idents.get(Consumer.begin()->getKey());
3304 else if (Consumer.size() > 1 && CTC == CTC_ObjCMessageReceiver
3305 && Consumer["super"]) {
3306 // Prefix 'super' when we're completing in a message-receiver
3307 // context.
3308 Res.suppressDiagnostics();
3309 Res.clear();
3311 // Don't correct to a keyword that's the same as the typo; the keyword
3312 // wasn't actually in scope.
3313 if (ED == 0) {
3314 Res.setLookupName(Typo);
3315 return DeclarationName();
3318 // Record the correction for unqualified lookup.
3319 if (IsUnqualifiedLookup)
3320 UnqualifiedTyposCorrected[Typo]
3321 = std::make_pair("super", Consumer.begin()->second);
3323 return &Context.Idents.get("super");
3326 Res.suppressDiagnostics();
3327 Res.setLookupName(Typo);
3328 Res.clear();
3329 // Record the correction for unqualified lookup.
3330 if (IsUnqualifiedLookup)
3331 (void)UnqualifiedTyposCorrected[Typo];
3333 return DeclarationName();