SemaLookup.cpp revision f4bae14c1c2cb086d42aecf84c6779787c6c7d89
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++. 12// 13//===----------------------------------------------------------------------===// 14#include "clang/Sema/Sema.h" 15#include "clang/Sema/Lookup.h" 16#include "clang/Sema/DeclSpec.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclCXX.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/DeclTemplate.h" 23#include "clang/AST/Expr.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/Basic/Builtins.h" 26#include "clang/Basic/LangOptions.h" 27#include "llvm/ADT/STLExtras.h" 28#include "llvm/ADT/SmallPtrSet.h" 29#include "llvm/Support/ErrorHandling.h" 30#include <list> 31#include <set> 32#include <vector> 33#include <iterator> 34#include <utility> 35#include <algorithm> 36 37using namespace clang; 38 39namespace { 40 class UnqualUsingEntry { 41 const DeclContext *Nominated; 42 const DeclContext *CommonAncestor; 43 44 public: 45 UnqualUsingEntry(const DeclContext *Nominated, 46 const DeclContext *CommonAncestor) 47 : Nominated(Nominated), CommonAncestor(CommonAncestor) { 48 } 49 50 const DeclContext *getCommonAncestor() const { 51 return CommonAncestor; 52 } 53 54 const DeclContext *getNominatedNamespace() const { 55 return Nominated; 56 } 57 58 // Sort by the pointer value of the common ancestor. 59 struct Comparator { 60 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) { 61 return L.getCommonAncestor() < R.getCommonAncestor(); 62 } 63 64 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) { 65 return E.getCommonAncestor() < DC; 66 } 67 68 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) { 69 return DC < E.getCommonAncestor(); 70 } 71 }; 72 }; 73 74 /// A collection of using directives, as used by C++ unqualified 75 /// lookup. 76 class UnqualUsingDirectiveSet { 77 typedef llvm::SmallVector<UnqualUsingEntry, 8> ListTy; 78 79 ListTy list; 80 llvm::SmallPtrSet<DeclContext*, 8> visited; 81 82 public: 83 UnqualUsingDirectiveSet() {} 84 85 void visitScopeChain(Scope *S, Scope *InnermostFileScope) { 86 // C++ [namespace.udir]p1: 87 // During unqualified name lookup, the names appear as if they 88 // were declared in the nearest enclosing namespace which contains 89 // both the using-directive and the nominated namespace. 90 DeclContext *InnermostFileDC 91 = static_cast<DeclContext*>(InnermostFileScope->getEntity()); 92 assert(InnermostFileDC && InnermostFileDC->isFileContext()); 93 94 for (; S; S = S->getParent()) { 95 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) { 96 DeclContext *EffectiveDC = (Ctx->isFileContext() ? Ctx : InnermostFileDC); 97 visit(Ctx, EffectiveDC); 98 } else { 99 Scope::udir_iterator I = S->using_directives_begin(), 100 End = S->using_directives_end(); 101 102 for (; I != End; ++I) 103 visit(*I, InnermostFileDC); 104 } 105 } 106 } 107 108 // Visits a context and collect all of its using directives 109 // recursively. Treats all using directives as if they were 110 // declared in the context. 111 // 112 // A given context is only every visited once, so it is important 113 // that contexts be visited from the inside out in order to get 114 // the effective DCs right. 115 void visit(DeclContext *DC, DeclContext *EffectiveDC) { 116 if (!visited.insert(DC)) 117 return; 118 119 addUsingDirectives(DC, EffectiveDC); 120 } 121 122 // Visits a using directive and collects all of its using 123 // directives recursively. Treats all using directives as if they 124 // were declared in the effective DC. 125 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 126 DeclContext *NS = UD->getNominatedNamespace(); 127 if (!visited.insert(NS)) 128 return; 129 130 addUsingDirective(UD, EffectiveDC); 131 addUsingDirectives(NS, EffectiveDC); 132 } 133 134 // Adds all the using directives in a context (and those nominated 135 // by its using directives, transitively) as if they appeared in 136 // the given effective context. 137 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { 138 llvm::SmallVector<DeclContext*,4> queue; 139 while (true) { 140 DeclContext::udir_iterator I, End; 141 for (llvm::tie(I, End) = DC->getUsingDirectives(); I != End; ++I) { 142 UsingDirectiveDecl *UD = *I; 143 DeclContext *NS = UD->getNominatedNamespace(); 144 if (visited.insert(NS)) { 145 addUsingDirective(UD, EffectiveDC); 146 queue.push_back(NS); 147 } 148 } 149 150 if (queue.empty()) 151 return; 152 153 DC = queue.back(); 154 queue.pop_back(); 155 } 156 } 157 158 // Add a using directive as if it had been declared in the given 159 // context. This helps implement C++ [namespace.udir]p3: 160 // The using-directive is transitive: if a scope contains a 161 // using-directive that nominates a second namespace that itself 162 // contains using-directives, the effect is as if the 163 // using-directives from the second namespace also appeared in 164 // the first. 165 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { 166 // Find the common ancestor between the effective context and 167 // the nominated namespace. 168 DeclContext *Common = UD->getNominatedNamespace(); 169 while (!Common->Encloses(EffectiveDC)) 170 Common = Common->getParent(); 171 Common = Common->getPrimaryContext(); 172 173 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); 174 } 175 176 void done() { 177 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator()); 178 } 179 180 typedef ListTy::iterator iterator; 181 typedef ListTy::const_iterator const_iterator; 182 183 iterator begin() { return list.begin(); } 184 iterator end() { return list.end(); } 185 const_iterator begin() const { return list.begin(); } 186 const_iterator end() const { return list.end(); } 187 188 std::pair<const_iterator,const_iterator> 189 getNamespacesFor(DeclContext *DC) const { 190 return std::equal_range(begin(), end(), DC->getPrimaryContext(), 191 UnqualUsingEntry::Comparator()); 192 } 193 }; 194} 195 196// Retrieve the set of identifier namespaces that correspond to a 197// specific kind of name lookup. 198static inline unsigned getIDNS(Sema::LookupNameKind NameKind, 199 bool CPlusPlus, 200 bool Redeclaration) { 201 unsigned IDNS = 0; 202 switch (NameKind) { 203 case Sema::LookupOrdinaryName: 204 case Sema::LookupRedeclarationWithLinkage: 205 IDNS = Decl::IDNS_Ordinary; 206 if (CPlusPlus) { 207 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; 208 if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; 209 } 210 break; 211 212 case Sema::LookupOperatorName: 213 // Operator lookup is its own crazy thing; it is not the same 214 // as (e.g.) looking up an operator name for redeclaration. 215 assert(!Redeclaration && "cannot do redeclaration operator lookup"); 216 IDNS = Decl::IDNS_NonMemberOperator; 217 break; 218 219 case Sema::LookupTagName: 220 if (CPlusPlus) { 221 IDNS = Decl::IDNS_Type; 222 223 // When looking for a redeclaration of a tag name, we add: 224 // 1) TagFriend to find undeclared friend decls 225 // 2) Namespace because they can't "overload" with tag decls. 226 // 3) Tag because it includes class templates, which can't 227 // "overload" with tag decls. 228 if (Redeclaration) 229 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; 230 } else { 231 IDNS = Decl::IDNS_Tag; 232 } 233 break; 234 235 case Sema::LookupMemberName: 236 IDNS = Decl::IDNS_Member; 237 if (CPlusPlus) 238 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; 239 break; 240 241 case Sema::LookupNestedNameSpecifierName: 242 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; 243 break; 244 245 case Sema::LookupNamespaceName: 246 IDNS = Decl::IDNS_Namespace; 247 break; 248 249 case Sema::LookupUsingDeclName: 250 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag 251 | Decl::IDNS_Member | Decl::IDNS_Using; 252 break; 253 254 case Sema::LookupObjCProtocolName: 255 IDNS = Decl::IDNS_ObjCProtocol; 256 break; 257 258 case Sema::LookupAnyName: 259 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member 260 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol 261 | Decl::IDNS_Type; 262 break; 263 } 264 return IDNS; 265} 266 267void LookupResult::configure() { 268 IDNS = getIDNS(LookupKind, 269 SemaRef.getLangOptions().CPlusPlus, 270 isForRedeclaration()); 271 272 // If we're looking for one of the allocation or deallocation 273 // operators, make sure that the implicitly-declared new and delete 274 // operators can be found. 275 if (!isForRedeclaration()) { 276 switch (NameInfo.getName().getCXXOverloadedOperator()) { 277 case OO_New: 278 case OO_Delete: 279 case OO_Array_New: 280 case OO_Array_Delete: 281 SemaRef.DeclareGlobalNewDelete(); 282 break; 283 284 default: 285 break; 286 } 287 } 288} 289 290// Necessary because CXXBasePaths is not complete in Sema.h 291void LookupResult::deletePaths(CXXBasePaths *Paths) { 292 delete Paths; 293} 294 295/// Resolves the result kind of this lookup. 296void LookupResult::resolveKind() { 297 unsigned N = Decls.size(); 298 299 // Fast case: no possible ambiguity. 300 if (N == 0) { 301 assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation); 302 return; 303 } 304 305 // If there's a single decl, we need to examine it to decide what 306 // kind of lookup this is. 307 if (N == 1) { 308 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl(); 309 if (isa<FunctionTemplateDecl>(D)) 310 ResultKind = FoundOverloaded; 311 else if (isa<UnresolvedUsingValueDecl>(D)) 312 ResultKind = FoundUnresolvedValue; 313 return; 314 } 315 316 // Don't do any extra resolution if we've already resolved as ambiguous. 317 if (ResultKind == Ambiguous) return; 318 319 llvm::SmallPtrSet<NamedDecl*, 16> Unique; 320 llvm::SmallPtrSet<QualType, 16> UniqueTypes; 321 322 bool Ambiguous = false; 323 bool HasTag = false, HasFunction = false, HasNonFunction = false; 324 bool HasFunctionTemplate = false, HasUnresolved = false; 325 326 unsigned UniqueTagIndex = 0; 327 328 unsigned I = 0; 329 while (I < N) { 330 NamedDecl *D = Decls[I]->getUnderlyingDecl(); 331 D = cast<NamedDecl>(D->getCanonicalDecl()); 332 333 // Redeclarations of types via typedef can occur both within a scope 334 // and, through using declarations and directives, across scopes. There is 335 // no ambiguity if they all refer to the same type, so unique based on the 336 // canonical type. 337 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) { 338 if (!TD->getDeclContext()->isRecord()) { 339 QualType T = SemaRef.Context.getTypeDeclType(TD); 340 if (!UniqueTypes.insert(SemaRef.Context.getCanonicalType(T))) { 341 // The type is not unique; pull something off the back and continue 342 // at this index. 343 Decls[I] = Decls[--N]; 344 continue; 345 } 346 } 347 } 348 349 if (!Unique.insert(D)) { 350 // If it's not unique, pull something off the back (and 351 // continue at this index). 352 Decls[I] = Decls[--N]; 353 continue; 354 } 355 356 // Otherwise, do some decl type analysis and then continue. 357 358 if (isa<UnresolvedUsingValueDecl>(D)) { 359 HasUnresolved = true; 360 } else if (isa<TagDecl>(D)) { 361 if (HasTag) 362 Ambiguous = true; 363 UniqueTagIndex = I; 364 HasTag = true; 365 } else if (isa<FunctionTemplateDecl>(D)) { 366 HasFunction = true; 367 HasFunctionTemplate = true; 368 } else if (isa<FunctionDecl>(D)) { 369 HasFunction = true; 370 } else { 371 if (HasNonFunction) 372 Ambiguous = true; 373 HasNonFunction = true; 374 } 375 I++; 376 } 377 378 // C++ [basic.scope.hiding]p2: 379 // A class name or enumeration name can be hidden by the name of 380 // an object, function, or enumerator declared in the same 381 // scope. If a class or enumeration name and an object, function, 382 // or enumerator are declared in the same scope (in any order) 383 // with the same name, the class or enumeration name is hidden 384 // wherever the object, function, or enumerator name is visible. 385 // But it's still an error if there are distinct tag types found, 386 // even if they're not visible. (ref?) 387 if (HideTags && HasTag && !Ambiguous && 388 (HasFunction || HasNonFunction || HasUnresolved)) 389 Decls[UniqueTagIndex] = Decls[--N]; 390 391 Decls.set_size(N); 392 393 if (HasNonFunction && (HasFunction || HasUnresolved)) 394 Ambiguous = true; 395 396 if (Ambiguous) 397 setAmbiguous(LookupResult::AmbiguousReference); 398 else if (HasUnresolved) 399 ResultKind = LookupResult::FoundUnresolvedValue; 400 else if (N > 1 || HasFunctionTemplate) 401 ResultKind = LookupResult::FoundOverloaded; 402 else 403 ResultKind = LookupResult::Found; 404} 405 406void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) { 407 CXXBasePaths::const_paths_iterator I, E; 408 DeclContext::lookup_iterator DI, DE; 409 for (I = P.begin(), E = P.end(); I != E; ++I) 410 for (llvm::tie(DI,DE) = I->Decls; DI != DE; ++DI) 411 addDecl(*DI); 412} 413 414void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { 415 Paths = new CXXBasePaths; 416 Paths->swap(P); 417 addDeclsFromBasePaths(*Paths); 418 resolveKind(); 419 setAmbiguous(AmbiguousBaseSubobjects); 420} 421 422void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { 423 Paths = new CXXBasePaths; 424 Paths->swap(P); 425 addDeclsFromBasePaths(*Paths); 426 resolveKind(); 427 setAmbiguous(AmbiguousBaseSubobjectTypes); 428} 429 430void LookupResult::print(llvm::raw_ostream &Out) { 431 Out << Decls.size() << " result(s)"; 432 if (isAmbiguous()) Out << ", ambiguous"; 433 if (Paths) Out << ", base paths present"; 434 435 for (iterator I = begin(), E = end(); I != E; ++I) { 436 Out << "\n"; 437 (*I)->print(Out, 2); 438 } 439} 440 441/// \brief Lookup a builtin function, when name lookup would otherwise 442/// fail. 443static bool LookupBuiltin(Sema &S, LookupResult &R) { 444 Sema::LookupNameKind NameKind = R.getLookupKind(); 445 446 // If we didn't find a use of this identifier, and if the identifier 447 // corresponds to a compiler builtin, create the decl object for the builtin 448 // now, injecting it into translation unit scope, and return it. 449 if (NameKind == Sema::LookupOrdinaryName || 450 NameKind == Sema::LookupRedeclarationWithLinkage) { 451 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo(); 452 if (II) { 453 // If this is a builtin on this (or all) targets, create the decl. 454 if (unsigned BuiltinID = II->getBuiltinID()) { 455 // In C++, we don't have any predefined library functions like 456 // 'malloc'. Instead, we'll just error. 457 if (S.getLangOptions().CPlusPlus && 458 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 459 return false; 460 461 NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 462 S.TUScope, R.isForRedeclaration(), 463 R.getNameLoc()); 464 if (D) 465 R.addDecl(D); 466 return (D != NULL); 467 } 468 } 469 } 470 471 return false; 472} 473 474/// \brief Determine whether we can declare a special member function within 475/// the class at this point. 476static bool CanDeclareSpecialMemberFunction(ASTContext &Context, 477 const CXXRecordDecl *Class) { 478 // Don't do it if the class is invalid. 479 if (Class->isInvalidDecl()) 480 return false; 481 482 // We need to have a definition for the class. 483 if (!Class->getDefinition() || Class->isDependentContext()) 484 return false; 485 486 // We can't be in the middle of defining the class. 487 if (const RecordType *RecordTy 488 = Context.getTypeDeclType(Class)->getAs<RecordType>()) 489 return !RecordTy->isBeingDefined(); 490 491 return false; 492} 493 494void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) { 495 if (!CanDeclareSpecialMemberFunction(Context, Class)) 496 return; 497 498 // If the default constructor has not yet been declared, do so now. 499 if (!Class->hasDeclaredDefaultConstructor()) 500 DeclareImplicitDefaultConstructor(Class); 501 502 // If the copy constructor has not yet been declared, do so now. 503 if (!Class->hasDeclaredCopyConstructor()) 504 DeclareImplicitCopyConstructor(Class); 505 506 // If the copy assignment operator has not yet been declared, do so now. 507 if (!Class->hasDeclaredCopyAssignment()) 508 DeclareImplicitCopyAssignment(Class); 509 510 // If the destructor has not yet been declared, do so now. 511 if (!Class->hasDeclaredDestructor()) 512 DeclareImplicitDestructor(Class); 513} 514 515/// \brief Determine whether this is the name of an implicitly-declared 516/// special member function. 517static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) { 518 switch (Name.getNameKind()) { 519 case DeclarationName::CXXConstructorName: 520 case DeclarationName::CXXDestructorName: 521 return true; 522 523 case DeclarationName::CXXOperatorName: 524 return Name.getCXXOverloadedOperator() == OO_Equal; 525 526 default: 527 break; 528 } 529 530 return false; 531} 532 533/// \brief If there are any implicit member functions with the given name 534/// that need to be declared in the given declaration context, do so. 535static void DeclareImplicitMemberFunctionsWithName(Sema &S, 536 DeclarationName Name, 537 const DeclContext *DC) { 538 if (!DC) 539 return; 540 541 switch (Name.getNameKind()) { 542 case DeclarationName::CXXConstructorName: 543 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 544 if (Record->getDefinition() && 545 CanDeclareSpecialMemberFunction(S.Context, Record)) { 546 if (!Record->hasDeclaredDefaultConstructor()) 547 S.DeclareImplicitDefaultConstructor( 548 const_cast<CXXRecordDecl *>(Record)); 549 if (!Record->hasDeclaredCopyConstructor()) 550 S.DeclareImplicitCopyConstructor(const_cast<CXXRecordDecl *>(Record)); 551 } 552 break; 553 554 case DeclarationName::CXXDestructorName: 555 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 556 if (Record->getDefinition() && !Record->hasDeclaredDestructor() && 557 CanDeclareSpecialMemberFunction(S.Context, Record)) 558 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record)); 559 break; 560 561 case DeclarationName::CXXOperatorName: 562 if (Name.getCXXOverloadedOperator() != OO_Equal) 563 break; 564 565 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 566 if (Record->getDefinition() && !Record->hasDeclaredCopyAssignment() && 567 CanDeclareSpecialMemberFunction(S.Context, Record)) 568 S.DeclareImplicitCopyAssignment(const_cast<CXXRecordDecl *>(Record)); 569 break; 570 571 default: 572 break; 573 } 574} 575 576// Adds all qualifying matches for a name within a decl context to the 577// given lookup result. Returns true if any matches were found. 578static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) { 579 bool Found = false; 580 581 // Lazily declare C++ special member functions. 582 if (S.getLangOptions().CPlusPlus) 583 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC); 584 585 // Perform lookup into this declaration context. 586 DeclContext::lookup_const_iterator I, E; 587 for (llvm::tie(I, E) = DC->lookup(R.getLookupName()); I != E; ++I) { 588 NamedDecl *D = *I; 589 if (R.isAcceptableDecl(D)) { 590 R.addDecl(D); 591 Found = true; 592 } 593 } 594 595 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R)) 596 return true; 597 598 if (R.getLookupName().getNameKind() 599 != DeclarationName::CXXConversionFunctionName || 600 R.getLookupName().getCXXNameType()->isDependentType() || 601 !isa<CXXRecordDecl>(DC)) 602 return Found; 603 604 // C++ [temp.mem]p6: 605 // A specialization of a conversion function template is not found by 606 // name lookup. Instead, any conversion function templates visible in the 607 // context of the use are considered. [...] 608 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 609 if (!Record->isDefinition()) 610 return Found; 611 612 const UnresolvedSetImpl *Unresolved = Record->getConversionFunctions(); 613 for (UnresolvedSetImpl::iterator U = Unresolved->begin(), 614 UEnd = Unresolved->end(); U != UEnd; ++U) { 615 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U); 616 if (!ConvTemplate) 617 continue; 618 619 // When we're performing lookup for the purposes of redeclaration, just 620 // add the conversion function template. When we deduce template 621 // arguments for specializations, we'll end up unifying the return 622 // type of the new declaration with the type of the function template. 623 if (R.isForRedeclaration()) { 624 R.addDecl(ConvTemplate); 625 Found = true; 626 continue; 627 } 628 629 // C++ [temp.mem]p6: 630 // [...] For each such operator, if argument deduction succeeds 631 // (14.9.2.3), the resulting specialization is used as if found by 632 // name lookup. 633 // 634 // When referencing a conversion function for any purpose other than 635 // a redeclaration (such that we'll be building an expression with the 636 // result), perform template argument deduction and place the 637 // specialization into the result set. We do this to avoid forcing all 638 // callers to perform special deduction for conversion functions. 639 Sema::TemplateDeductionInfo Info(R.getSema().Context, R.getNameLoc()); 640 FunctionDecl *Specialization = 0; 641 642 const FunctionProtoType *ConvProto 643 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>(); 644 assert(ConvProto && "Nonsensical conversion function template type"); 645 646 // Compute the type of the function that we would expect the conversion 647 // function to have, if it were to match the name given. 648 // FIXME: Calling convention! 649 FunctionType::ExtInfo ConvProtoInfo = ConvProto->getExtInfo(); 650 QualType ExpectedType 651 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(), 652 0, 0, ConvProto->isVariadic(), 653 ConvProto->getTypeQuals(), 654 false, false, 0, 0, 655 ConvProtoInfo.withCallingConv(CC_Default)); 656 657 // Perform template argument deduction against the type that we would 658 // expect the function to have. 659 if (R.getSema().DeduceTemplateArguments(ConvTemplate, 0, ExpectedType, 660 Specialization, Info) 661 == Sema::TDK_Success) { 662 R.addDecl(Specialization); 663 Found = true; 664 } 665 } 666 667 return Found; 668} 669 670// Performs C++ unqualified lookup into the given file context. 671static bool 672CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, 673 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) { 674 675 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); 676 677 // Perform direct name lookup into the LookupCtx. 678 bool Found = LookupDirect(S, R, NS); 679 680 // Perform direct name lookup into the namespaces nominated by the 681 // using directives whose common ancestor is this namespace. 682 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 683 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(NS); 684 685 for (; UI != UEnd; ++UI) 686 if (LookupDirect(S, R, UI->getNominatedNamespace())) 687 Found = true; 688 689 R.resolveKind(); 690 691 return Found; 692} 693 694static bool isNamespaceOrTranslationUnitScope(Scope *S) { 695 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 696 return Ctx->isFileContext(); 697 return false; 698} 699 700// Find the next outer declaration context from this scope. This 701// routine actually returns the semantic outer context, which may 702// differ from the lexical context (encoded directly in the Scope 703// stack) when we are parsing a member of a class template. In this 704// case, the second element of the pair will be true, to indicate that 705// name lookup should continue searching in this semantic context when 706// it leaves the current template parameter scope. 707static std::pair<DeclContext *, bool> findOuterContext(Scope *S) { 708 DeclContext *DC = static_cast<DeclContext *>(S->getEntity()); 709 DeclContext *Lexical = 0; 710 for (Scope *OuterS = S->getParent(); OuterS; 711 OuterS = OuterS->getParent()) { 712 if (OuterS->getEntity()) { 713 Lexical = static_cast<DeclContext *>(OuterS->getEntity()); 714 break; 715 } 716 } 717 718 // C++ [temp.local]p8: 719 // In the definition of a member of a class template that appears 720 // outside of the namespace containing the class template 721 // definition, the name of a template-parameter hides the name of 722 // a member of this namespace. 723 // 724 // Example: 725 // 726 // namespace N { 727 // class C { }; 728 // 729 // template<class T> class B { 730 // void f(T); 731 // }; 732 // } 733 // 734 // template<class C> void N::B<C>::f(C) { 735 // C b; // C is the template parameter, not N::C 736 // } 737 // 738 // In this example, the lexical context we return is the 739 // TranslationUnit, while the semantic context is the namespace N. 740 if (!Lexical || !DC || !S->getParent() || 741 !S->getParent()->isTemplateParamScope()) 742 return std::make_pair(Lexical, false); 743 744 // Find the outermost template parameter scope. 745 // For the example, this is the scope for the template parameters of 746 // template<class C>. 747 Scope *OutermostTemplateScope = S->getParent(); 748 while (OutermostTemplateScope->getParent() && 749 OutermostTemplateScope->getParent()->isTemplateParamScope()) 750 OutermostTemplateScope = OutermostTemplateScope->getParent(); 751 752 // Find the namespace context in which the original scope occurs. In 753 // the example, this is namespace N. 754 DeclContext *Semantic = DC; 755 while (!Semantic->isFileContext()) 756 Semantic = Semantic->getParent(); 757 758 // Find the declaration context just outside of the template 759 // parameter scope. This is the context in which the template is 760 // being lexically declaration (a namespace context). In the 761 // example, this is the global scope. 762 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) && 763 Lexical->Encloses(Semantic)) 764 return std::make_pair(Semantic, true); 765 766 return std::make_pair(Lexical, false); 767} 768 769bool Sema::CppLookupName(LookupResult &R, Scope *S) { 770 assert(getLangOptions().CPlusPlus && "Can perform only C++ lookup"); 771 772 DeclarationName Name = R.getLookupName(); 773 774 // If this is the name of an implicitly-declared special member function, 775 // go through the scope stack to implicitly declare 776 if (isImplicitlyDeclaredMemberFunctionName(Name)) { 777 for (Scope *PreS = S; PreS; PreS = PreS->getParent()) 778 if (DeclContext *DC = static_cast<DeclContext *>(PreS->getEntity())) 779 DeclareImplicitMemberFunctionsWithName(*this, Name, DC); 780 } 781 782 // Implicitly declare member functions with the name we're looking for, if in 783 // fact we are in a scope where it matters. 784 785 Scope *Initial = S; 786 IdentifierResolver::iterator 787 I = IdResolver.begin(Name), 788 IEnd = IdResolver.end(); 789 790 // First we lookup local scope. 791 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] 792 // ...During unqualified name lookup (3.4.1), the names appear as if 793 // they were declared in the nearest enclosing namespace which contains 794 // both the using-directive and the nominated namespace. 795 // [Note: in this context, "contains" means "contains directly or 796 // indirectly". 797 // 798 // For example: 799 // namespace A { int i; } 800 // void foo() { 801 // int i; 802 // { 803 // using namespace A; 804 // ++i; // finds local 'i', A::i appears at global scope 805 // } 806 // } 807 // 808 DeclContext *OutsideOfTemplateParamDC = 0; 809 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { 810 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 811 812 // Check whether the IdResolver has anything in this scope. 813 bool Found = false; 814 for (; I != IEnd && S->isDeclScope(*I); ++I) { 815 if (R.isAcceptableDecl(*I)) { 816 Found = true; 817 R.addDecl(*I); 818 } 819 } 820 if (Found) { 821 R.resolveKind(); 822 if (S->isClassScope()) 823 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx)) 824 R.setNamingClass(Record); 825 return true; 826 } 827 828 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 829 S->getParent() && !S->getParent()->isTemplateParamScope()) { 830 // We've just searched the last template parameter scope and 831 // found nothing, so look into the the contexts between the 832 // lexical and semantic declaration contexts returned by 833 // findOuterContext(). This implements the name lookup behavior 834 // of C++ [temp.local]p8. 835 Ctx = OutsideOfTemplateParamDC; 836 OutsideOfTemplateParamDC = 0; 837 } 838 839 if (Ctx) { 840 DeclContext *OuterCtx; 841 bool SearchAfterTemplateScope; 842 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 843 if (SearchAfterTemplateScope) 844 OutsideOfTemplateParamDC = OuterCtx; 845 846 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 847 // We do not directly look into transparent contexts, since 848 // those entities will be found in the nearest enclosing 849 // non-transparent context. 850 if (Ctx->isTransparentContext()) 851 continue; 852 853 // We do not look directly into function or method contexts, 854 // since all of the local variables and parameters of the 855 // function/method are present within the Scope. 856 if (Ctx->isFunctionOrMethod()) { 857 // If we have an Objective-C instance method, look for ivars 858 // in the corresponding interface. 859 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 860 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo()) 861 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) { 862 ObjCInterfaceDecl *ClassDeclared; 863 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable( 864 Name.getAsIdentifierInfo(), 865 ClassDeclared)) { 866 if (R.isAcceptableDecl(Ivar)) { 867 R.addDecl(Ivar); 868 R.resolveKind(); 869 return true; 870 } 871 } 872 } 873 } 874 875 continue; 876 } 877 878 // Perform qualified name lookup into this context. 879 // FIXME: In some cases, we know that every name that could be found by 880 // this qualified name lookup will also be on the identifier chain. For 881 // example, inside a class without any base classes, we never need to 882 // perform qualified lookup because all of the members are on top of the 883 // identifier chain. 884 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true)) 885 return true; 886 } 887 } 888 } 889 890 // Stop if we ran out of scopes. 891 // FIXME: This really, really shouldn't be happening. 892 if (!S) return false; 893 894 // Collect UsingDirectiveDecls in all scopes, and recursively all 895 // nominated namespaces by those using-directives. 896 // 897 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we 898 // don't build it for each lookup! 899 900 UnqualUsingDirectiveSet UDirs; 901 UDirs.visitScopeChain(Initial, S); 902 UDirs.done(); 903 904 // Lookup namespace scope, and global scope. 905 // Unqualified name lookup in C++ requires looking into scopes 906 // that aren't strictly lexical, and therefore we walk through the 907 // context as well as walking through the scopes. 908 909 for (; S; S = S->getParent()) { 910 // Check whether the IdResolver has anything in this scope. 911 bool Found = false; 912 for (; I != IEnd && S->isDeclScope(*I); ++I) { 913 if (R.isAcceptableDecl(*I)) { 914 // We found something. Look for anything else in our scope 915 // with this same name and in an acceptable identifier 916 // namespace, so that we can construct an overload set if we 917 // need to. 918 Found = true; 919 R.addDecl(*I); 920 } 921 } 922 923 if (Found && S->isTemplateParamScope()) { 924 R.resolveKind(); 925 return true; 926 } 927 928 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 929 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && 930 S->getParent() && !S->getParent()->isTemplateParamScope()) { 931 // We've just searched the last template parameter scope and 932 // found nothing, so look into the the contexts between the 933 // lexical and semantic declaration contexts returned by 934 // findOuterContext(). This implements the name lookup behavior 935 // of C++ [temp.local]p8. 936 Ctx = OutsideOfTemplateParamDC; 937 OutsideOfTemplateParamDC = 0; 938 } 939 940 if (Ctx) { 941 DeclContext *OuterCtx; 942 bool SearchAfterTemplateScope; 943 llvm::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); 944 if (SearchAfterTemplateScope) 945 OutsideOfTemplateParamDC = OuterCtx; 946 947 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { 948 // We do not directly look into transparent contexts, since 949 // those entities will be found in the nearest enclosing 950 // non-transparent context. 951 if (Ctx->isTransparentContext()) 952 continue; 953 954 // If we have a context, and it's not a context stashed in the 955 // template parameter scope for an out-of-line definition, also 956 // look into that context. 957 if (!(Found && S && S->isTemplateParamScope())) { 958 assert(Ctx->isFileContext() && 959 "We should have been looking only at file context here already."); 960 961 // Look into context considering using-directives. 962 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) 963 Found = true; 964 } 965 966 if (Found) { 967 R.resolveKind(); 968 return true; 969 } 970 971 if (R.isForRedeclaration() && !Ctx->isTransparentContext()) 972 return false; 973 } 974 } 975 976 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext()) 977 return false; 978 } 979 980 return !R.empty(); 981} 982 983/// @brief Perform unqualified name lookup starting from a given 984/// scope. 985/// 986/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is 987/// used to find names within the current scope. For example, 'x' in 988/// @code 989/// int x; 990/// int f() { 991/// return x; // unqualified name look finds 'x' in the global scope 992/// } 993/// @endcode 994/// 995/// Different lookup criteria can find different names. For example, a 996/// particular scope can have both a struct and a function of the same 997/// name, and each can be found by certain lookup criteria. For more 998/// information about lookup criteria, see the documentation for the 999/// class LookupCriteria. 1000/// 1001/// @param S The scope from which unqualified name lookup will 1002/// begin. If the lookup criteria permits, name lookup may also search 1003/// in the parent scopes. 1004/// 1005/// @param Name The name of the entity that we are searching for. 1006/// 1007/// @param Loc If provided, the source location where we're performing 1008/// name lookup. At present, this is only used to produce diagnostics when 1009/// C library functions (like "malloc") are implicitly declared. 1010/// 1011/// @returns The result of name lookup, which includes zero or more 1012/// declarations and possibly additional information used to diagnose 1013/// ambiguities. 1014bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { 1015 DeclarationName Name = R.getLookupName(); 1016 if (!Name) return false; 1017 1018 LookupNameKind NameKind = R.getLookupKind(); 1019 1020 if (!getLangOptions().CPlusPlus) { 1021 // Unqualified name lookup in C/Objective-C is purely lexical, so 1022 // search in the declarations attached to the name. 1023 1024 if (NameKind == Sema::LookupRedeclarationWithLinkage) { 1025 // Find the nearest non-transparent declaration scope. 1026 while (!(S->getFlags() & Scope::DeclScope) || 1027 (S->getEntity() && 1028 static_cast<DeclContext *>(S->getEntity()) 1029 ->isTransparentContext())) 1030 S = S->getParent(); 1031 } 1032 1033 unsigned IDNS = R.getIdentifierNamespace(); 1034 1035 // Scan up the scope chain looking for a decl that matches this 1036 // identifier that is in the appropriate namespace. This search 1037 // should not take long, as shadowing of names is uncommon, and 1038 // deep shadowing is extremely uncommon. 1039 bool LeftStartingScope = false; 1040 1041 for (IdentifierResolver::iterator I = IdResolver.begin(Name), 1042 IEnd = IdResolver.end(); 1043 I != IEnd; ++I) 1044 if ((*I)->isInIdentifierNamespace(IDNS)) { 1045 if (NameKind == LookupRedeclarationWithLinkage) { 1046 // Determine whether this (or a previous) declaration is 1047 // out-of-scope. 1048 if (!LeftStartingScope && !S->isDeclScope(*I)) 1049 LeftStartingScope = true; 1050 1051 // If we found something outside of our starting scope that 1052 // does not have linkage, skip it. 1053 if (LeftStartingScope && !((*I)->hasLinkage())) 1054 continue; 1055 } 1056 1057 R.addDecl(*I); 1058 1059 if ((*I)->getAttr<OverloadableAttr>()) { 1060 // If this declaration has the "overloadable" attribute, we 1061 // might have a set of overloaded functions. 1062 1063 // Figure out what scope the identifier is in. 1064 while (!(S->getFlags() & Scope::DeclScope) || 1065 !S->isDeclScope(*I)) 1066 S = S->getParent(); 1067 1068 // Find the last declaration in this scope (with the same 1069 // name, naturally). 1070 IdentifierResolver::iterator LastI = I; 1071 for (++LastI; LastI != IEnd; ++LastI) { 1072 if (!S->isDeclScope(*LastI)) 1073 break; 1074 R.addDecl(*LastI); 1075 } 1076 } 1077 1078 R.resolveKind(); 1079 1080 return true; 1081 } 1082 } else { 1083 // Perform C++ unqualified name lookup. 1084 if (CppLookupName(R, S)) 1085 return true; 1086 } 1087 1088 // If we didn't find a use of this identifier, and if the identifier 1089 // corresponds to a compiler builtin, create the decl object for the builtin 1090 // now, injecting it into translation unit scope, and return it. 1091 if (AllowBuiltinCreation) 1092 return LookupBuiltin(*this, R); 1093 1094 return false; 1095} 1096 1097/// @brief Perform qualified name lookup in the namespaces nominated by 1098/// using directives by the given context. 1099/// 1100/// C++98 [namespace.qual]p2: 1101/// Given X::m (where X is a user-declared namespace), or given ::m 1102/// (where X is the global namespace), let S be the set of all 1103/// declarations of m in X and in the transitive closure of all 1104/// namespaces nominated by using-directives in X and its used 1105/// namespaces, except that using-directives are ignored in any 1106/// namespace, including X, directly containing one or more 1107/// declarations of m. No namespace is searched more than once in 1108/// the lookup of a name. If S is the empty set, the program is 1109/// ill-formed. Otherwise, if S has exactly one member, or if the 1110/// context of the reference is a using-declaration 1111/// (namespace.udecl), S is the required set of declarations of 1112/// m. Otherwise if the use of m is not one that allows a unique 1113/// declaration to be chosen from S, the program is ill-formed. 1114/// C++98 [namespace.qual]p5: 1115/// During the lookup of a qualified namespace member name, if the 1116/// lookup finds more than one declaration of the member, and if one 1117/// declaration introduces a class name or enumeration name and the 1118/// other declarations either introduce the same object, the same 1119/// enumerator or a set of functions, the non-type name hides the 1120/// class or enumeration name if and only if the declarations are 1121/// from the same namespace; otherwise (the declarations are from 1122/// different namespaces), the program is ill-formed. 1123static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, 1124 DeclContext *StartDC) { 1125 assert(StartDC->isFileContext() && "start context is not a file context"); 1126 1127 DeclContext::udir_iterator I = StartDC->using_directives_begin(); 1128 DeclContext::udir_iterator E = StartDC->using_directives_end(); 1129 1130 if (I == E) return false; 1131 1132 // We have at least added all these contexts to the queue. 1133 llvm::DenseSet<DeclContext*> Visited; 1134 Visited.insert(StartDC); 1135 1136 // We have not yet looked into these namespaces, much less added 1137 // their "using-children" to the queue. 1138 llvm::SmallVector<NamespaceDecl*, 8> Queue; 1139 1140 // We have already looked into the initial namespace; seed the queue 1141 // with its using-children. 1142 for (; I != E; ++I) { 1143 NamespaceDecl *ND = (*I)->getNominatedNamespace()->getOriginalNamespace(); 1144 if (Visited.insert(ND).second) 1145 Queue.push_back(ND); 1146 } 1147 1148 // The easiest way to implement the restriction in [namespace.qual]p5 1149 // is to check whether any of the individual results found a tag 1150 // and, if so, to declare an ambiguity if the final result is not 1151 // a tag. 1152 bool FoundTag = false; 1153 bool FoundNonTag = false; 1154 1155 LookupResult LocalR(LookupResult::Temporary, R); 1156 1157 bool Found = false; 1158 while (!Queue.empty()) { 1159 NamespaceDecl *ND = Queue.back(); 1160 Queue.pop_back(); 1161 1162 // We go through some convolutions here to avoid copying results 1163 // between LookupResults. 1164 bool UseLocal = !R.empty(); 1165 LookupResult &DirectR = UseLocal ? LocalR : R; 1166 bool FoundDirect = LookupDirect(S, DirectR, ND); 1167 1168 if (FoundDirect) { 1169 // First do any local hiding. 1170 DirectR.resolveKind(); 1171 1172 // If the local result is a tag, remember that. 1173 if (DirectR.isSingleTagDecl()) 1174 FoundTag = true; 1175 else 1176 FoundNonTag = true; 1177 1178 // Append the local results to the total results if necessary. 1179 if (UseLocal) { 1180 R.addAllDecls(LocalR); 1181 LocalR.clear(); 1182 } 1183 } 1184 1185 // If we find names in this namespace, ignore its using directives. 1186 if (FoundDirect) { 1187 Found = true; 1188 continue; 1189 } 1190 1191 for (llvm::tie(I,E) = ND->getUsingDirectives(); I != E; ++I) { 1192 NamespaceDecl *Nom = (*I)->getNominatedNamespace(); 1193 if (Visited.insert(Nom).second) 1194 Queue.push_back(Nom); 1195 } 1196 } 1197 1198 if (Found) { 1199 if (FoundTag && FoundNonTag) 1200 R.setAmbiguousQualifiedTagHiding(); 1201 else 1202 R.resolveKind(); 1203 } 1204 1205 return Found; 1206} 1207 1208/// \brief Callback that looks for any member of a class with the given name. 1209static bool LookupAnyMember(const CXXBaseSpecifier *Specifier, 1210 CXXBasePath &Path, 1211 void *Name) { 1212 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 1213 1214 DeclarationName N = DeclarationName::getFromOpaquePtr(Name); 1215 Path.Decls = BaseRecord->lookup(N); 1216 return Path.Decls.first != Path.Decls.second; 1217} 1218 1219/// \brief Perform qualified name lookup into a given context. 1220/// 1221/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find 1222/// names when the context of those names is explicit specified, e.g., 1223/// "std::vector" or "x->member", or as part of unqualified name lookup. 1224/// 1225/// Different lookup criteria can find different names. For example, a 1226/// particular scope can have both a struct and a function of the same 1227/// name, and each can be found by certain lookup criteria. For more 1228/// information about lookup criteria, see the documentation for the 1229/// class LookupCriteria. 1230/// 1231/// \param R captures both the lookup criteria and any lookup results found. 1232/// 1233/// \param LookupCtx The context in which qualified name lookup will 1234/// search. If the lookup criteria permits, name lookup may also search 1235/// in the parent contexts or (for C++ classes) base classes. 1236/// 1237/// \param InUnqualifiedLookup true if this is qualified name lookup that 1238/// occurs as part of unqualified name lookup. 1239/// 1240/// \returns true if lookup succeeded, false if it failed. 1241bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 1242 bool InUnqualifiedLookup) { 1243 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); 1244 1245 if (!R.getLookupName()) 1246 return false; 1247 1248 // Make sure that the declaration context is complete. 1249 assert((!isa<TagDecl>(LookupCtx) || 1250 LookupCtx->isDependentContext() || 1251 cast<TagDecl>(LookupCtx)->isDefinition() || 1252 Context.getTypeDeclType(cast<TagDecl>(LookupCtx))->getAs<TagType>() 1253 ->isBeingDefined()) && 1254 "Declaration context must already be complete!"); 1255 1256 // Perform qualified name lookup into the LookupCtx. 1257 if (LookupDirect(*this, R, LookupCtx)) { 1258 R.resolveKind(); 1259 if (isa<CXXRecordDecl>(LookupCtx)) 1260 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx)); 1261 return true; 1262 } 1263 1264 // Don't descend into implied contexts for redeclarations. 1265 // C++98 [namespace.qual]p6: 1266 // In a declaration for a namespace member in which the 1267 // declarator-id is a qualified-id, given that the qualified-id 1268 // for the namespace member has the form 1269 // nested-name-specifier unqualified-id 1270 // the unqualified-id shall name a member of the namespace 1271 // designated by the nested-name-specifier. 1272 // See also [class.mfct]p5 and [class.static.data]p2. 1273 if (R.isForRedeclaration()) 1274 return false; 1275 1276 // If this is a namespace, look it up in the implied namespaces. 1277 if (LookupCtx->isFileContext()) 1278 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx); 1279 1280 // If this isn't a C++ class, we aren't allowed to look into base 1281 // classes, we're done. 1282 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx); 1283 if (!LookupRec || !LookupRec->getDefinition()) 1284 return false; 1285 1286 // If we're performing qualified name lookup into a dependent class, 1287 // then we are actually looking into a current instantiation. If we have any 1288 // dependent base classes, then we either have to delay lookup until 1289 // template instantiation time (at which point all bases will be available) 1290 // or we have to fail. 1291 if (!InUnqualifiedLookup && LookupRec->isDependentContext() && 1292 LookupRec->hasAnyDependentBases()) { 1293 R.setNotFoundInCurrentInstantiation(); 1294 return false; 1295 } 1296 1297 // Perform lookup into our base classes. 1298 CXXBasePaths Paths; 1299 Paths.setOrigin(LookupRec); 1300 1301 // Look for this member in our base classes 1302 CXXRecordDecl::BaseMatchesCallback *BaseCallback = 0; 1303 switch (R.getLookupKind()) { 1304 case LookupOrdinaryName: 1305 case LookupMemberName: 1306 case LookupRedeclarationWithLinkage: 1307 BaseCallback = &CXXRecordDecl::FindOrdinaryMember; 1308 break; 1309 1310 case LookupTagName: 1311 BaseCallback = &CXXRecordDecl::FindTagMember; 1312 break; 1313 1314 case LookupAnyName: 1315 BaseCallback = &LookupAnyMember; 1316 break; 1317 1318 case LookupUsingDeclName: 1319 // This lookup is for redeclarations only. 1320 1321 case LookupOperatorName: 1322 case LookupNamespaceName: 1323 case LookupObjCProtocolName: 1324 // These lookups will never find a member in a C++ class (or base class). 1325 return false; 1326 1327 case LookupNestedNameSpecifierName: 1328 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember; 1329 break; 1330 } 1331 1332 if (!LookupRec->lookupInBases(BaseCallback, 1333 R.getLookupName().getAsOpaquePtr(), Paths)) 1334 return false; 1335 1336 R.setNamingClass(LookupRec); 1337 1338 // C++ [class.member.lookup]p2: 1339 // [...] If the resulting set of declarations are not all from 1340 // sub-objects of the same type, or the set has a nonstatic member 1341 // and includes members from distinct sub-objects, there is an 1342 // ambiguity and the program is ill-formed. Otherwise that set is 1343 // the result of the lookup. 1344 // FIXME: support using declarations! 1345 QualType SubobjectType; 1346 int SubobjectNumber = 0; 1347 AccessSpecifier SubobjectAccess = AS_none; 1348 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); 1349 Path != PathEnd; ++Path) { 1350 const CXXBasePathElement &PathElement = Path->back(); 1351 1352 // Pick the best (i.e. most permissive i.e. numerically lowest) access 1353 // across all paths. 1354 SubobjectAccess = std::min(SubobjectAccess, Path->Access); 1355 1356 // Determine whether we're looking at a distinct sub-object or not. 1357 if (SubobjectType.isNull()) { 1358 // This is the first subobject we've looked at. Record its type. 1359 SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); 1360 SubobjectNumber = PathElement.SubobjectNumber; 1361 } else if (SubobjectType 1362 != Context.getCanonicalType(PathElement.Base->getType())) { 1363 // We found members of the given name in two subobjects of 1364 // different types. This lookup is ambiguous. 1365 R.setAmbiguousBaseSubobjectTypes(Paths); 1366 return true; 1367 } else if (SubobjectNumber != PathElement.SubobjectNumber) { 1368 // We have a different subobject of the same type. 1369 1370 // C++ [class.member.lookup]p5: 1371 // A static member, a nested type or an enumerator defined in 1372 // a base class T can unambiguously be found even if an object 1373 // has more than one base class subobject of type T. 1374 Decl *FirstDecl = *Path->Decls.first; 1375 if (isa<VarDecl>(FirstDecl) || 1376 isa<TypeDecl>(FirstDecl) || 1377 isa<EnumConstantDecl>(FirstDecl)) 1378 continue; 1379 1380 if (isa<CXXMethodDecl>(FirstDecl)) { 1381 // Determine whether all of the methods are static. 1382 bool AllMethodsAreStatic = true; 1383 for (DeclContext::lookup_iterator Func = Path->Decls.first; 1384 Func != Path->Decls.second; ++Func) { 1385 if (!isa<CXXMethodDecl>(*Func)) { 1386 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl"); 1387 break; 1388 } 1389 1390 if (!cast<CXXMethodDecl>(*Func)->isStatic()) { 1391 AllMethodsAreStatic = false; 1392 break; 1393 } 1394 } 1395 1396 if (AllMethodsAreStatic) 1397 continue; 1398 } 1399 1400 // We have found a nonstatic member name in multiple, distinct 1401 // subobjects. Name lookup is ambiguous. 1402 R.setAmbiguousBaseSubobjects(Paths); 1403 return true; 1404 } 1405 } 1406 1407 // Lookup in a base class succeeded; return these results. 1408 1409 DeclContext::lookup_iterator I, E; 1410 for (llvm::tie(I,E) = Paths.front().Decls; I != E; ++I) { 1411 NamedDecl *D = *I; 1412 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, 1413 D->getAccess()); 1414 R.addDecl(D, AS); 1415 } 1416 R.resolveKind(); 1417 return true; 1418} 1419 1420/// @brief Performs name lookup for a name that was parsed in the 1421/// source code, and may contain a C++ scope specifier. 1422/// 1423/// This routine is a convenience routine meant to be called from 1424/// contexts that receive a name and an optional C++ scope specifier 1425/// (e.g., "N::M::x"). It will then perform either qualified or 1426/// unqualified name lookup (with LookupQualifiedName or LookupName, 1427/// respectively) on the given name and return those results. 1428/// 1429/// @param S The scope from which unqualified name lookup will 1430/// begin. 1431/// 1432/// @param SS An optional C++ scope-specifier, e.g., "::N::M". 1433/// 1434/// @param Name The name of the entity that name lookup will 1435/// search for. 1436/// 1437/// @param Loc If provided, the source location where we're performing 1438/// name lookup. At present, this is only used to produce diagnostics when 1439/// C library functions (like "malloc") are implicitly declared. 1440/// 1441/// @param EnteringContext Indicates whether we are going to enter the 1442/// context of the scope-specifier SS (if present). 1443/// 1444/// @returns True if any decls were found (but possibly ambiguous) 1445bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 1446 bool AllowBuiltinCreation, bool EnteringContext) { 1447 if (SS && SS->isInvalid()) { 1448 // When the scope specifier is invalid, don't even look for 1449 // anything. 1450 return false; 1451 } 1452 1453 if (SS && SS->isSet()) { 1454 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { 1455 // We have resolved the scope specifier to a particular declaration 1456 // contex, and will perform name lookup in that context. 1457 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) 1458 return false; 1459 1460 R.setContextRange(SS->getRange()); 1461 1462 return LookupQualifiedName(R, DC); 1463 } 1464 1465 // We could not resolve the scope specified to a specific declaration 1466 // context, which means that SS refers to an unknown specialization. 1467 // Name lookup can't find anything in this case. 1468 return false; 1469 } 1470 1471 // Perform unqualified name lookup starting in the given scope. 1472 return LookupName(R, S, AllowBuiltinCreation); 1473} 1474 1475 1476/// @brief Produce a diagnostic describing the ambiguity that resulted 1477/// from name lookup. 1478/// 1479/// @param Result The ambiguous name lookup result. 1480/// 1481/// @param Name The name of the entity that name lookup was 1482/// searching for. 1483/// 1484/// @param NameLoc The location of the name within the source code. 1485/// 1486/// @param LookupRange A source range that provides more 1487/// source-location information concerning the lookup itself. For 1488/// example, this range might highlight a nested-name-specifier that 1489/// precedes the name. 1490/// 1491/// @returns true 1492bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { 1493 assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); 1494 1495 DeclarationName Name = Result.getLookupName(); 1496 SourceLocation NameLoc = Result.getNameLoc(); 1497 SourceRange LookupRange = Result.getContextRange(); 1498 1499 switch (Result.getAmbiguityKind()) { 1500 case LookupResult::AmbiguousBaseSubobjects: { 1501 CXXBasePaths *Paths = Result.getBasePaths(); 1502 QualType SubobjectType = Paths->front().back().Base->getType(); 1503 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) 1504 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) 1505 << LookupRange; 1506 1507 DeclContext::lookup_iterator Found = Paths->front().Decls.first; 1508 while (isa<CXXMethodDecl>(*Found) && 1509 cast<CXXMethodDecl>(*Found)->isStatic()) 1510 ++Found; 1511 1512 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); 1513 1514 return true; 1515 } 1516 1517 case LookupResult::AmbiguousBaseSubobjectTypes: { 1518 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) 1519 << Name << LookupRange; 1520 1521 CXXBasePaths *Paths = Result.getBasePaths(); 1522 std::set<Decl *> DeclsPrinted; 1523 for (CXXBasePaths::paths_iterator Path = Paths->begin(), 1524 PathEnd = Paths->end(); 1525 Path != PathEnd; ++Path) { 1526 Decl *D = *Path->Decls.first; 1527 if (DeclsPrinted.insert(D).second) 1528 Diag(D->getLocation(), diag::note_ambiguous_member_found); 1529 } 1530 1531 return true; 1532 } 1533 1534 case LookupResult::AmbiguousTagHiding: { 1535 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; 1536 1537 llvm::SmallPtrSet<NamedDecl*,8> TagDecls; 1538 1539 LookupResult::iterator DI, DE = Result.end(); 1540 for (DI = Result.begin(); DI != DE; ++DI) 1541 if (TagDecl *TD = dyn_cast<TagDecl>(*DI)) { 1542 TagDecls.insert(TD); 1543 Diag(TD->getLocation(), diag::note_hidden_tag); 1544 } 1545 1546 for (DI = Result.begin(); DI != DE; ++DI) 1547 if (!isa<TagDecl>(*DI)) 1548 Diag((*DI)->getLocation(), diag::note_hiding_object); 1549 1550 // For recovery purposes, go ahead and implement the hiding. 1551 LookupResult::Filter F = Result.makeFilter(); 1552 while (F.hasNext()) { 1553 if (TagDecls.count(F.next())) 1554 F.erase(); 1555 } 1556 F.done(); 1557 1558 return true; 1559 } 1560 1561 case LookupResult::AmbiguousReference: { 1562 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; 1563 1564 LookupResult::iterator DI = Result.begin(), DE = Result.end(); 1565 for (; DI != DE; ++DI) 1566 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI; 1567 1568 return true; 1569 } 1570 } 1571 1572 llvm_unreachable("unknown ambiguity kind"); 1573 return true; 1574} 1575 1576namespace { 1577 struct AssociatedLookup { 1578 AssociatedLookup(Sema &S, 1579 Sema::AssociatedNamespaceSet &Namespaces, 1580 Sema::AssociatedClassSet &Classes) 1581 : S(S), Namespaces(Namespaces), Classes(Classes) { 1582 } 1583 1584 Sema &S; 1585 Sema::AssociatedNamespaceSet &Namespaces; 1586 Sema::AssociatedClassSet &Classes; 1587 }; 1588} 1589 1590static void 1591addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); 1592 1593static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, 1594 DeclContext *Ctx) { 1595 // Add the associated namespace for this class. 1596 1597 // We don't use DeclContext::getEnclosingNamespaceContext() as this may 1598 // be a locally scoped record. 1599 1600 while (Ctx->isRecord() || Ctx->isTransparentContext()) 1601 Ctx = Ctx->getParent(); 1602 1603 if (Ctx->isFileContext()) 1604 Namespaces.insert(Ctx->getPrimaryContext()); 1605} 1606 1607// \brief Add the associated classes and namespaces for argument-dependent 1608// lookup that involves a template argument (C++ [basic.lookup.koenig]p2). 1609static void 1610addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 1611 const TemplateArgument &Arg) { 1612 // C++ [basic.lookup.koenig]p2, last bullet: 1613 // -- [...] ; 1614 switch (Arg.getKind()) { 1615 case TemplateArgument::Null: 1616 break; 1617 1618 case TemplateArgument::Type: 1619 // [...] the namespaces and classes associated with the types of the 1620 // template arguments provided for template type parameters (excluding 1621 // template template parameters) 1622 addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); 1623 break; 1624 1625 case TemplateArgument::Template: { 1626 // [...] the namespaces in which any template template arguments are 1627 // defined; and the classes in which any member templates used as 1628 // template template arguments are defined. 1629 TemplateName Template = Arg.getAsTemplate(); 1630 if (ClassTemplateDecl *ClassTemplate 1631 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { 1632 DeclContext *Ctx = ClassTemplate->getDeclContext(); 1633 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1634 Result.Classes.insert(EnclosingClass); 1635 // Add the associated namespace for this class. 1636 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1637 } 1638 break; 1639 } 1640 1641 case TemplateArgument::Declaration: 1642 case TemplateArgument::Integral: 1643 case TemplateArgument::Expression: 1644 // [Note: non-type template arguments do not contribute to the set of 1645 // associated namespaces. ] 1646 break; 1647 1648 case TemplateArgument::Pack: 1649 for (TemplateArgument::pack_iterator P = Arg.pack_begin(), 1650 PEnd = Arg.pack_end(); 1651 P != PEnd; ++P) 1652 addAssociatedClassesAndNamespaces(Result, *P); 1653 break; 1654 } 1655} 1656 1657// \brief Add the associated classes and namespaces for 1658// argument-dependent lookup with an argument of class type 1659// (C++ [basic.lookup.koenig]p2). 1660static void 1661addAssociatedClassesAndNamespaces(AssociatedLookup &Result, 1662 CXXRecordDecl *Class) { 1663 1664 // Just silently ignore anything whose name is __va_list_tag. 1665 if (Class->getDeclName() == Result.S.VAListTagName) 1666 return; 1667 1668 // C++ [basic.lookup.koenig]p2: 1669 // [...] 1670 // -- If T is a class type (including unions), its associated 1671 // classes are: the class itself; the class of which it is a 1672 // member, if any; and its direct and indirect base 1673 // classes. Its associated namespaces are the namespaces in 1674 // which its associated classes are defined. 1675 1676 // Add the class of which it is a member, if any. 1677 DeclContext *Ctx = Class->getDeclContext(); 1678 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1679 Result.Classes.insert(EnclosingClass); 1680 // Add the associated namespace for this class. 1681 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1682 1683 // Add the class itself. If we've already seen this class, we don't 1684 // need to visit base classes. 1685 if (!Result.Classes.insert(Class)) 1686 return; 1687 1688 // -- If T is a template-id, its associated namespaces and classes are 1689 // the namespace in which the template is defined; for member 1690 // templates, the member template’s class; the namespaces and classes 1691 // associated with the types of the template arguments provided for 1692 // template type parameters (excluding template template parameters); the 1693 // namespaces in which any template template arguments are defined; and 1694 // the classes in which any member templates used as template template 1695 // arguments are defined. [Note: non-type template arguments do not 1696 // contribute to the set of associated namespaces. ] 1697 if (ClassTemplateSpecializationDecl *Spec 1698 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { 1699 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); 1700 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1701 Result.Classes.insert(EnclosingClass); 1702 // Add the associated namespace for this class. 1703 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1704 1705 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1706 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 1707 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); 1708 } 1709 1710 // Only recurse into base classes for complete types. 1711 if (!Class->hasDefinition()) { 1712 // FIXME: we might need to instantiate templates here 1713 return; 1714 } 1715 1716 // Add direct and indirect base classes along with their associated 1717 // namespaces. 1718 llvm::SmallVector<CXXRecordDecl *, 32> Bases; 1719 Bases.push_back(Class); 1720 while (!Bases.empty()) { 1721 // Pop this class off the stack. 1722 Class = Bases.back(); 1723 Bases.pop_back(); 1724 1725 // Visit the base classes. 1726 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(), 1727 BaseEnd = Class->bases_end(); 1728 Base != BaseEnd; ++Base) { 1729 const RecordType *BaseType = Base->getType()->getAs<RecordType>(); 1730 // In dependent contexts, we do ADL twice, and the first time around, 1731 // the base type might be a dependent TemplateSpecializationType, or a 1732 // TemplateTypeParmType. If that happens, simply ignore it. 1733 // FIXME: If we want to support export, we probably need to add the 1734 // namespace of the template in a TemplateSpecializationType, or even 1735 // the classes and namespaces of known non-dependent arguments. 1736 if (!BaseType) 1737 continue; 1738 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 1739 if (Result.Classes.insert(BaseDecl)) { 1740 // Find the associated namespace for this base class. 1741 DeclContext *BaseCtx = BaseDecl->getDeclContext(); 1742 CollectEnclosingNamespace(Result.Namespaces, BaseCtx); 1743 1744 // Make sure we visit the bases of this base class. 1745 if (BaseDecl->bases_begin() != BaseDecl->bases_end()) 1746 Bases.push_back(BaseDecl); 1747 } 1748 } 1749 } 1750} 1751 1752// \brief Add the associated classes and namespaces for 1753// argument-dependent lookup with an argument of type T 1754// (C++ [basic.lookup.koenig]p2). 1755static void 1756addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { 1757 // C++ [basic.lookup.koenig]p2: 1758 // 1759 // For each argument type T in the function call, there is a set 1760 // of zero or more associated namespaces and a set of zero or more 1761 // associated classes to be considered. The sets of namespaces and 1762 // classes is determined entirely by the types of the function 1763 // arguments (and the namespace of any template template 1764 // argument). Typedef names and using-declarations used to specify 1765 // the types do not contribute to this set. The sets of namespaces 1766 // and classes are determined in the following way: 1767 1768 llvm::SmallVector<const Type *, 16> Queue; 1769 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); 1770 1771 while (true) { 1772 switch (T->getTypeClass()) { 1773 1774#define TYPE(Class, Base) 1775#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1776#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 1777#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 1778#define ABSTRACT_TYPE(Class, Base) 1779#include "clang/AST/TypeNodes.def" 1780 // T is canonical. We can also ignore dependent types because 1781 // we don't need to do ADL at the definition point, but if we 1782 // wanted to implement template export (or if we find some other 1783 // use for associated classes and namespaces...) this would be 1784 // wrong. 1785 break; 1786 1787 // -- If T is a pointer to U or an array of U, its associated 1788 // namespaces and classes are those associated with U. 1789 case Type::Pointer: 1790 T = cast<PointerType>(T)->getPointeeType().getTypePtr(); 1791 continue; 1792 case Type::ConstantArray: 1793 case Type::IncompleteArray: 1794 case Type::VariableArray: 1795 T = cast<ArrayType>(T)->getElementType().getTypePtr(); 1796 continue; 1797 1798 // -- If T is a fundamental type, its associated sets of 1799 // namespaces and classes are both empty. 1800 case Type::Builtin: 1801 break; 1802 1803 // -- If T is a class type (including unions), its associated 1804 // classes are: the class itself; the class of which it is a 1805 // member, if any; and its direct and indirect base 1806 // classes. Its associated namespaces are the namespaces in 1807 // which its associated classes are defined. 1808 case Type::Record: { 1809 CXXRecordDecl *Class 1810 = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); 1811 addAssociatedClassesAndNamespaces(Result, Class); 1812 break; 1813 } 1814 1815 // -- If T is an enumeration type, its associated namespace is 1816 // the namespace in which it is defined. If it is class 1817 // member, its associated class is the member’s class; else 1818 // it has no associated class. 1819 case Type::Enum: { 1820 EnumDecl *Enum = cast<EnumType>(T)->getDecl(); 1821 1822 DeclContext *Ctx = Enum->getDeclContext(); 1823 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) 1824 Result.Classes.insert(EnclosingClass); 1825 1826 // Add the associated namespace for this class. 1827 CollectEnclosingNamespace(Result.Namespaces, Ctx); 1828 1829 break; 1830 } 1831 1832 // -- If T is a function type, its associated namespaces and 1833 // classes are those associated with the function parameter 1834 // types and those associated with the return type. 1835 case Type::FunctionProto: { 1836 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 1837 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(), 1838 ArgEnd = Proto->arg_type_end(); 1839 Arg != ArgEnd; ++Arg) 1840 Queue.push_back(Arg->getTypePtr()); 1841 // fallthrough 1842 } 1843 case Type::FunctionNoProto: { 1844 const FunctionType *FnType = cast<FunctionType>(T); 1845 T = FnType->getResultType().getTypePtr(); 1846 continue; 1847 } 1848 1849 // -- If T is a pointer to a member function of a class X, its 1850 // associated namespaces and classes are those associated 1851 // with the function parameter types and return type, 1852 // together with those associated with X. 1853 // 1854 // -- If T is a pointer to a data member of class X, its 1855 // associated namespaces and classes are those associated 1856 // with the member type together with those associated with 1857 // X. 1858 case Type::MemberPointer: { 1859 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); 1860 1861 // Queue up the class type into which this points. 1862 Queue.push_back(MemberPtr->getClass()); 1863 1864 // And directly continue with the pointee type. 1865 T = MemberPtr->getPointeeType().getTypePtr(); 1866 continue; 1867 } 1868 1869 // As an extension, treat this like a normal pointer. 1870 case Type::BlockPointer: 1871 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); 1872 continue; 1873 1874 // References aren't covered by the standard, but that's such an 1875 // obvious defect that we cover them anyway. 1876 case Type::LValueReference: 1877 case Type::RValueReference: 1878 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); 1879 continue; 1880 1881 // These are fundamental types. 1882 case Type::Vector: 1883 case Type::ExtVector: 1884 case Type::Complex: 1885 break; 1886 1887 // These are ignored by ADL. 1888 case Type::ObjCObject: 1889 case Type::ObjCInterface: 1890 case Type::ObjCObjectPointer: 1891 break; 1892 } 1893 1894 if (Queue.empty()) break; 1895 T = Queue.back(); 1896 Queue.pop_back(); 1897 } 1898} 1899 1900/// \brief Find the associated classes and namespaces for 1901/// argument-dependent lookup for a call with the given set of 1902/// arguments. 1903/// 1904/// This routine computes the sets of associated classes and associated 1905/// namespaces searched by argument-dependent lookup 1906/// (C++ [basic.lookup.argdep]) for a given set of arguments. 1907void 1908Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs, 1909 AssociatedNamespaceSet &AssociatedNamespaces, 1910 AssociatedClassSet &AssociatedClasses) { 1911 AssociatedNamespaces.clear(); 1912 AssociatedClasses.clear(); 1913 1914 AssociatedLookup Result(*this, AssociatedNamespaces, AssociatedClasses); 1915 1916 // C++ [basic.lookup.koenig]p2: 1917 // For each argument type T in the function call, there is a set 1918 // of zero or more associated namespaces and a set of zero or more 1919 // associated classes to be considered. The sets of namespaces and 1920 // classes is determined entirely by the types of the function 1921 // arguments (and the namespace of any template template 1922 // argument). 1923 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) { 1924 Expr *Arg = Args[ArgIdx]; 1925 1926 if (Arg->getType() != Context.OverloadTy) { 1927 addAssociatedClassesAndNamespaces(Result, Arg->getType()); 1928 continue; 1929 } 1930 1931 // [...] In addition, if the argument is the name or address of a 1932 // set of overloaded functions and/or function templates, its 1933 // associated classes and namespaces are the union of those 1934 // associated with each of the members of the set: the namespace 1935 // in which the function or function template is defined and the 1936 // classes and namespaces associated with its (non-dependent) 1937 // parameter types and return type. 1938 Arg = Arg->IgnoreParens(); 1939 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) 1940 if (unaryOp->getOpcode() == UnaryOperator::AddrOf) 1941 Arg = unaryOp->getSubExpr(); 1942 1943 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg); 1944 if (!ULE) continue; 1945 1946 for (UnresolvedSetIterator I = ULE->decls_begin(), E = ULE->decls_end(); 1947 I != E; ++I) { 1948 // Look through any using declarations to find the underlying function. 1949 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 1950 1951 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Fn); 1952 if (!FDecl) 1953 FDecl = cast<FunctionTemplateDecl>(Fn)->getTemplatedDecl(); 1954 1955 // Add the classes and namespaces associated with the parameter 1956 // types and return type of this function. 1957 addAssociatedClassesAndNamespaces(Result, FDecl->getType()); 1958 } 1959 } 1960} 1961 1962/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 1963/// an acceptable non-member overloaded operator for a call whose 1964/// arguments have types T1 (and, if non-empty, T2). This routine 1965/// implements the check in C++ [over.match.oper]p3b2 concerning 1966/// enumeration types. 1967static bool 1968IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, 1969 QualType T1, QualType T2, 1970 ASTContext &Context) { 1971 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 1972 return true; 1973 1974 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 1975 return true; 1976 1977 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 1978 if (Proto->getNumArgs() < 1) 1979 return false; 1980 1981 if (T1->isEnumeralType()) { 1982 QualType ArgType = Proto->getArgType(0).getNonReferenceType(); 1983 if (Context.hasSameUnqualifiedType(T1, ArgType)) 1984 return true; 1985 } 1986 1987 if (Proto->getNumArgs() < 2) 1988 return false; 1989 1990 if (!T2.isNull() && T2->isEnumeralType()) { 1991 QualType ArgType = Proto->getArgType(1).getNonReferenceType(); 1992 if (Context.hasSameUnqualifiedType(T2, ArgType)) 1993 return true; 1994 } 1995 1996 return false; 1997} 1998 1999NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, 2000 SourceLocation Loc, 2001 LookupNameKind NameKind, 2002 RedeclarationKind Redecl) { 2003 LookupResult R(*this, Name, Loc, NameKind, Redecl); 2004 LookupName(R, S); 2005 return R.getAsSingle<NamedDecl>(); 2006} 2007 2008/// \brief Find the protocol with the given name, if any. 2009ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, 2010 SourceLocation IdLoc) { 2011 Decl *D = LookupSingleName(TUScope, II, IdLoc, 2012 LookupObjCProtocolName); 2013 return cast_or_null<ObjCProtocolDecl>(D); 2014} 2015 2016void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2017 QualType T1, QualType T2, 2018 UnresolvedSetImpl &Functions) { 2019 // C++ [over.match.oper]p3: 2020 // -- The set of non-member candidates is the result of the 2021 // unqualified lookup of operator@ in the context of the 2022 // expression according to the usual rules for name lookup in 2023 // unqualified function calls (3.4.2) except that all member 2024 // functions are ignored. However, if no operand has a class 2025 // type, only those non-member functions in the lookup set 2026 // that have a first parameter of type T1 or "reference to 2027 // (possibly cv-qualified) T1", when T1 is an enumeration 2028 // type, or (if there is a right operand) a second parameter 2029 // of type T2 or "reference to (possibly cv-qualified) T2", 2030 // when T2 is an enumeration type, are candidate functions. 2031 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2032 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); 2033 LookupName(Operators, S); 2034 2035 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); 2036 2037 if (Operators.empty()) 2038 return; 2039 2040 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end(); 2041 Op != OpEnd; ++Op) { 2042 NamedDecl *Found = (*Op)->getUnderlyingDecl(); 2043 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Found)) { 2044 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) 2045 Functions.addDecl(*Op, Op.getAccess()); // FIXME: canonical FD 2046 } else if (FunctionTemplateDecl *FunTmpl 2047 = dyn_cast<FunctionTemplateDecl>(Found)) { 2048 // FIXME: friend operators? 2049 // FIXME: do we need to check IsAcceptableNonMemberOperatorCandidate, 2050 // later? 2051 if (!FunTmpl->getDeclContext()->isRecord()) 2052 Functions.addDecl(*Op, Op.getAccess()); 2053 } 2054 } 2055} 2056 2057/// \brief Look up the constructors for the given class. 2058DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { 2059 // If the copy constructor has not yet been declared, do so now. 2060 if (CanDeclareSpecialMemberFunction(Context, Class)) { 2061 if (!Class->hasDeclaredDefaultConstructor()) 2062 DeclareImplicitDefaultConstructor(Class); 2063 if (!Class->hasDeclaredCopyConstructor()) 2064 DeclareImplicitCopyConstructor(Class); 2065 } 2066 2067 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); 2068 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); 2069 return Class->lookup(Name); 2070} 2071 2072/// \brief Look for the destructor of the given class. 2073/// 2074/// During semantic analysis, this routine should be used in lieu of 2075/// CXXRecordDecl::getDestructor(). 2076/// 2077/// \returns The destructor for this class. 2078CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { 2079 // If the destructor has not yet been declared, do so now. 2080 if (CanDeclareSpecialMemberFunction(Context, Class) && 2081 !Class->hasDeclaredDestructor()) 2082 DeclareImplicitDestructor(Class); 2083 2084 return Class->getDestructor(); 2085} 2086 2087void ADLResult::insert(NamedDecl *New) { 2088 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; 2089 2090 // If we haven't yet seen a decl for this key, or the last decl 2091 // was exactly this one, we're done. 2092 if (Old == 0 || Old == New) { 2093 Old = New; 2094 return; 2095 } 2096 2097 // Otherwise, decide which is a more recent redeclaration. 2098 FunctionDecl *OldFD, *NewFD; 2099 if (isa<FunctionTemplateDecl>(New)) { 2100 OldFD = cast<FunctionTemplateDecl>(Old)->getTemplatedDecl(); 2101 NewFD = cast<FunctionTemplateDecl>(New)->getTemplatedDecl(); 2102 } else { 2103 OldFD = cast<FunctionDecl>(Old); 2104 NewFD = cast<FunctionDecl>(New); 2105 } 2106 2107 FunctionDecl *Cursor = NewFD; 2108 while (true) { 2109 Cursor = Cursor->getPreviousDeclaration(); 2110 2111 // If we got to the end without finding OldFD, OldFD is the newer 2112 // declaration; leave things as they are. 2113 if (!Cursor) return; 2114 2115 // If we do find OldFD, then NewFD is newer. 2116 if (Cursor == OldFD) break; 2117 2118 // Otherwise, keep looking. 2119 } 2120 2121 Old = New; 2122} 2123 2124void Sema::ArgumentDependentLookup(DeclarationName Name, bool Operator, 2125 Expr **Args, unsigned NumArgs, 2126 ADLResult &Result) { 2127 // Find all of the associated namespaces and classes based on the 2128 // arguments we have. 2129 AssociatedNamespaceSet AssociatedNamespaces; 2130 AssociatedClassSet AssociatedClasses; 2131 FindAssociatedClassesAndNamespaces(Args, NumArgs, 2132 AssociatedNamespaces, 2133 AssociatedClasses); 2134 2135 QualType T1, T2; 2136 if (Operator) { 2137 T1 = Args[0]->getType(); 2138 if (NumArgs >= 2) 2139 T2 = Args[1]->getType(); 2140 } 2141 2142 // C++ [basic.lookup.argdep]p3: 2143 // Let X be the lookup set produced by unqualified lookup (3.4.1) 2144 // and let Y be the lookup set produced by argument dependent 2145 // lookup (defined as follows). If X contains [...] then Y is 2146 // empty. Otherwise Y is the set of declarations found in the 2147 // namespaces associated with the argument types as described 2148 // below. The set of declarations found by the lookup of the name 2149 // is the union of X and Y. 2150 // 2151 // Here, we compute Y and add its members to the overloaded 2152 // candidate set. 2153 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(), 2154 NSEnd = AssociatedNamespaces.end(); 2155 NS != NSEnd; ++NS) { 2156 // When considering an associated namespace, the lookup is the 2157 // same as the lookup performed when the associated namespace is 2158 // used as a qualifier (3.4.3.2) except that: 2159 // 2160 // -- Any using-directives in the associated namespace are 2161 // ignored. 2162 // 2163 // -- Any namespace-scope friend functions declared in 2164 // associated classes are visible within their respective 2165 // namespaces even if they are not visible during an ordinary 2166 // lookup (11.4). 2167 DeclContext::lookup_iterator I, E; 2168 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) { 2169 NamedDecl *D = *I; 2170 // If the only declaration here is an ordinary friend, consider 2171 // it only if it was declared in an associated classes. 2172 if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) { 2173 DeclContext *LexDC = D->getLexicalDeclContext(); 2174 if (!AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) 2175 continue; 2176 } 2177 2178 if (isa<UsingShadowDecl>(D)) 2179 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2180 2181 if (isa<FunctionDecl>(D)) { 2182 if (Operator && 2183 !IsAcceptableNonMemberOperatorCandidate(cast<FunctionDecl>(D), 2184 T1, T2, Context)) 2185 continue; 2186 } else if (!isa<FunctionTemplateDecl>(D)) 2187 continue; 2188 2189 Result.insert(D); 2190 } 2191 } 2192} 2193 2194//---------------------------------------------------------------------------- 2195// Search for all visible declarations. 2196//---------------------------------------------------------------------------- 2197VisibleDeclConsumer::~VisibleDeclConsumer() { } 2198 2199namespace { 2200 2201class ShadowContextRAII; 2202 2203class VisibleDeclsRecord { 2204public: 2205 /// \brief An entry in the shadow map, which is optimized to store a 2206 /// single declaration (the common case) but can also store a list 2207 /// of declarations. 2208 class ShadowMapEntry { 2209 typedef llvm::SmallVector<NamedDecl *, 4> DeclVector; 2210 2211 /// \brief Contains either the solitary NamedDecl * or a vector 2212 /// of declarations. 2213 llvm::PointerUnion<NamedDecl *, DeclVector*> DeclOrVector; 2214 2215 public: 2216 ShadowMapEntry() : DeclOrVector() { } 2217 2218 void Add(NamedDecl *ND); 2219 void Destroy(); 2220 2221 // Iteration. 2222 typedef NamedDecl **iterator; 2223 iterator begin(); 2224 iterator end(); 2225 }; 2226 2227private: 2228 /// \brief A mapping from declaration names to the declarations that have 2229 /// this name within a particular scope. 2230 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 2231 2232 /// \brief A list of shadow maps, which is used to model name hiding. 2233 std::list<ShadowMap> ShadowMaps; 2234 2235 /// \brief The declaration contexts we have already visited. 2236 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; 2237 2238 friend class ShadowContextRAII; 2239 2240public: 2241 /// \brief Determine whether we have already visited this context 2242 /// (and, if not, note that we are going to visit that context now). 2243 bool visitedContext(DeclContext *Ctx) { 2244 return !VisitedContexts.insert(Ctx); 2245 } 2246 2247 bool alreadyVisitedContext(DeclContext *Ctx) { 2248 return VisitedContexts.count(Ctx); 2249 } 2250 2251 /// \brief Determine whether the given declaration is hidden in the 2252 /// current scope. 2253 /// 2254 /// \returns the declaration that hides the given declaration, or 2255 /// NULL if no such declaration exists. 2256 NamedDecl *checkHidden(NamedDecl *ND); 2257 2258 /// \brief Add a declaration to the current shadow map. 2259 void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].Add(ND); } 2260}; 2261 2262/// \brief RAII object that records when we've entered a shadow context. 2263class ShadowContextRAII { 2264 VisibleDeclsRecord &Visible; 2265 2266 typedef VisibleDeclsRecord::ShadowMap ShadowMap; 2267 2268public: 2269 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { 2270 Visible.ShadowMaps.push_back(ShadowMap()); 2271 } 2272 2273 ~ShadowContextRAII() { 2274 for (ShadowMap::iterator E = Visible.ShadowMaps.back().begin(), 2275 EEnd = Visible.ShadowMaps.back().end(); 2276 E != EEnd; 2277 ++E) 2278 E->second.Destroy(); 2279 2280 Visible.ShadowMaps.pop_back(); 2281 } 2282}; 2283 2284} // end anonymous namespace 2285 2286void VisibleDeclsRecord::ShadowMapEntry::Add(NamedDecl *ND) { 2287 if (DeclOrVector.isNull()) { 2288 // 0 - > 1 elements: just set the single element information. 2289 DeclOrVector = ND; 2290 return; 2291 } 2292 2293 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) { 2294 // 1 -> 2 elements: create the vector of results and push in the 2295 // existing declaration. 2296 DeclVector *Vec = new DeclVector; 2297 Vec->push_back(PrevND); 2298 DeclOrVector = Vec; 2299 } 2300 2301 // Add the new element to the end of the vector. 2302 DeclOrVector.get<DeclVector*>()->push_back(ND); 2303} 2304 2305void VisibleDeclsRecord::ShadowMapEntry::Destroy() { 2306 if (DeclVector *Vec = DeclOrVector.dyn_cast<DeclVector *>()) { 2307 delete Vec; 2308 DeclOrVector = ((NamedDecl *)0); 2309 } 2310} 2311 2312VisibleDeclsRecord::ShadowMapEntry::iterator 2313VisibleDeclsRecord::ShadowMapEntry::begin() { 2314 if (DeclOrVector.isNull()) 2315 return 0; 2316 2317 if (DeclOrVector.dyn_cast<NamedDecl *>()) 2318 return &reinterpret_cast<NamedDecl*&>(DeclOrVector); 2319 2320 return DeclOrVector.get<DeclVector *>()->begin(); 2321} 2322 2323VisibleDeclsRecord::ShadowMapEntry::iterator 2324VisibleDeclsRecord::ShadowMapEntry::end() { 2325 if (DeclOrVector.isNull()) 2326 return 0; 2327 2328 if (DeclOrVector.dyn_cast<NamedDecl *>()) 2329 return &reinterpret_cast<NamedDecl*&>(DeclOrVector) + 1; 2330 2331 return DeclOrVector.get<DeclVector *>()->end(); 2332} 2333 2334NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { 2335 // Look through using declarations. 2336 ND = ND->getUnderlyingDecl(); 2337 2338 unsigned IDNS = ND->getIdentifierNamespace(); 2339 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); 2340 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); 2341 SM != SMEnd; ++SM) { 2342 ShadowMap::iterator Pos = SM->find(ND->getDeclName()); 2343 if (Pos == SM->end()) 2344 continue; 2345 2346 for (ShadowMapEntry::iterator I = Pos->second.begin(), 2347 IEnd = Pos->second.end(); 2348 I != IEnd; ++I) { 2349 // A tag declaration does not hide a non-tag declaration. 2350 if ((*I)->hasTagIdentifierNamespace() && 2351 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 2352 Decl::IDNS_ObjCProtocol))) 2353 continue; 2354 2355 // Protocols are in distinct namespaces from everything else. 2356 if ((((*I)->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 2357 || (IDNS & Decl::IDNS_ObjCProtocol)) && 2358 (*I)->getIdentifierNamespace() != IDNS) 2359 continue; 2360 2361 // Functions and function templates in the same scope overload 2362 // rather than hide. FIXME: Look for hiding based on function 2363 // signatures! 2364 if ((*I)->isFunctionOrFunctionTemplate() && 2365 ND->isFunctionOrFunctionTemplate() && 2366 SM == ShadowMaps.rbegin()) 2367 continue; 2368 2369 // We've found a declaration that hides this one. 2370 return *I; 2371 } 2372 } 2373 2374 return 0; 2375} 2376 2377static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, 2378 bool QualifiedNameLookup, 2379 bool InBaseClass, 2380 VisibleDeclConsumer &Consumer, 2381 VisibleDeclsRecord &Visited) { 2382 if (!Ctx) 2383 return; 2384 2385 // Make sure we don't visit the same context twice. 2386 if (Visited.visitedContext(Ctx->getPrimaryContext())) 2387 return; 2388 2389 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) 2390 Result.getSema().ForceDeclarationOfImplicitMembers(Class); 2391 2392 // Enumerate all of the results in this context. 2393 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx; 2394 CurCtx = CurCtx->getNextContext()) { 2395 for (DeclContext::decl_iterator D = CurCtx->decls_begin(), 2396 DEnd = CurCtx->decls_end(); 2397 D != DEnd; ++D) { 2398 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 2399 if (Result.isAcceptableDecl(ND)) { 2400 Consumer.FoundDecl(ND, Visited.checkHidden(ND), InBaseClass); 2401 Visited.add(ND); 2402 } 2403 2404 // Visit transparent contexts inside this context. 2405 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) { 2406 if (InnerCtx->isTransparentContext()) 2407 LookupVisibleDecls(InnerCtx, Result, QualifiedNameLookup, InBaseClass, 2408 Consumer, Visited); 2409 } 2410 } 2411 } 2412 2413 // Traverse using directives for qualified name lookup. 2414 if (QualifiedNameLookup) { 2415 ShadowContextRAII Shadow(Visited); 2416 DeclContext::udir_iterator I, E; 2417 for (llvm::tie(I, E) = Ctx->getUsingDirectives(); I != E; ++I) { 2418 LookupVisibleDecls((*I)->getNominatedNamespace(), Result, 2419 QualifiedNameLookup, InBaseClass, Consumer, Visited); 2420 } 2421 } 2422 2423 // Traverse the contexts of inherited C++ classes. 2424 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 2425 if (!Record->hasDefinition()) 2426 return; 2427 2428 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(), 2429 BEnd = Record->bases_end(); 2430 B != BEnd; ++B) { 2431 QualType BaseType = B->getType(); 2432 2433 // Don't look into dependent bases, because name lookup can't look 2434 // there anyway. 2435 if (BaseType->isDependentType()) 2436 continue; 2437 2438 const RecordType *Record = BaseType->getAs<RecordType>(); 2439 if (!Record) 2440 continue; 2441 2442 // FIXME: It would be nice to be able to determine whether referencing 2443 // a particular member would be ambiguous. For example, given 2444 // 2445 // struct A { int member; }; 2446 // struct B { int member; }; 2447 // struct C : A, B { }; 2448 // 2449 // void f(C *c) { c->### } 2450 // 2451 // accessing 'member' would result in an ambiguity. However, we 2452 // could be smart enough to qualify the member with the base 2453 // class, e.g., 2454 // 2455 // c->B::member 2456 // 2457 // or 2458 // 2459 // c->A::member 2460 2461 // Find results in this base class (and its bases). 2462 ShadowContextRAII Shadow(Visited); 2463 LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup, 2464 true, Consumer, Visited); 2465 } 2466 } 2467 2468 // Traverse the contexts of Objective-C classes. 2469 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { 2470 // Traverse categories. 2471 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); 2472 Category; Category = Category->getNextClassCategory()) { 2473 ShadowContextRAII Shadow(Visited); 2474 LookupVisibleDecls(Category, Result, QualifiedNameLookup, false, 2475 Consumer, Visited); 2476 } 2477 2478 // Traverse protocols. 2479 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(), 2480 E = IFace->protocol_end(); I != E; ++I) { 2481 ShadowContextRAII Shadow(Visited); 2482 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 2483 Visited); 2484 } 2485 2486 // Traverse the superclass. 2487 if (IFace->getSuperClass()) { 2488 ShadowContextRAII Shadow(Visited); 2489 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup, 2490 true, Consumer, Visited); 2491 } 2492 2493 // If there is an implementation, traverse it. We do this to find 2494 // synthesized ivars. 2495 if (IFace->getImplementation()) { 2496 ShadowContextRAII Shadow(Visited); 2497 LookupVisibleDecls(IFace->getImplementation(), Result, 2498 QualifiedNameLookup, true, Consumer, Visited); 2499 } 2500 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { 2501 for (ObjCProtocolDecl::protocol_iterator I = Protocol->protocol_begin(), 2502 E = Protocol->protocol_end(); I != E; ++I) { 2503 ShadowContextRAII Shadow(Visited); 2504 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 2505 Visited); 2506 } 2507 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { 2508 for (ObjCCategoryDecl::protocol_iterator I = Category->protocol_begin(), 2509 E = Category->protocol_end(); I != E; ++I) { 2510 ShadowContextRAII Shadow(Visited); 2511 LookupVisibleDecls(*I, Result, QualifiedNameLookup, false, Consumer, 2512 Visited); 2513 } 2514 2515 // If there is an implementation, traverse it. 2516 if (Category->getImplementation()) { 2517 ShadowContextRAII Shadow(Visited); 2518 LookupVisibleDecls(Category->getImplementation(), Result, 2519 QualifiedNameLookup, true, Consumer, Visited); 2520 } 2521 } 2522} 2523 2524static void LookupVisibleDecls(Scope *S, LookupResult &Result, 2525 UnqualUsingDirectiveSet &UDirs, 2526 VisibleDeclConsumer &Consumer, 2527 VisibleDeclsRecord &Visited) { 2528 if (!S) 2529 return; 2530 2531 if (!S->getEntity() || 2532 (!S->getParent() && 2533 !Visited.alreadyVisitedContext((DeclContext *)S->getEntity())) || 2534 ((DeclContext *)S->getEntity())->isFunctionOrMethod()) { 2535 // Walk through the declarations in this Scope. 2536 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 2537 D != DEnd; ++D) { 2538 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 2539 if (Result.isAcceptableDecl(ND)) { 2540 Consumer.FoundDecl(ND, Visited.checkHidden(ND), false); 2541 Visited.add(ND); 2542 } 2543 } 2544 } 2545 2546 // FIXME: C++ [temp.local]p8 2547 DeclContext *Entity = 0; 2548 if (S->getEntity()) { 2549 // Look into this scope's declaration context, along with any of its 2550 // parent lookup contexts (e.g., enclosing classes), up to the point 2551 // where we hit the context stored in the next outer scope. 2552 Entity = (DeclContext *)S->getEntity(); 2553 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME 2554 2555 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); 2556 Ctx = Ctx->getLookupParent()) { 2557 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { 2558 if (Method->isInstanceMethod()) { 2559 // For instance methods, look for ivars in the method's interface. 2560 LookupResult IvarResult(Result.getSema(), Result.getLookupName(), 2561 Result.getNameLoc(), Sema::LookupMemberName); 2562 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) 2563 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false, 2564 /*InBaseClass=*/false, Consumer, Visited); 2565 } 2566 2567 // We've already performed all of the name lookup that we need 2568 // to for Objective-C methods; the next context will be the 2569 // outer scope. 2570 break; 2571 } 2572 2573 if (Ctx->isFunctionOrMethod()) 2574 continue; 2575 2576 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false, 2577 /*InBaseClass=*/false, Consumer, Visited); 2578 } 2579 } else if (!S->getParent()) { 2580 // Look into the translation unit scope. We walk through the translation 2581 // unit's declaration context, because the Scope itself won't have all of 2582 // the declarations if we loaded a precompiled header. 2583 // FIXME: We would like the translation unit's Scope object to point to the 2584 // translation unit, so we don't need this special "if" branch. However, 2585 // doing so would force the normal C++ name-lookup code to look into the 2586 // translation unit decl when the IdentifierInfo chains would suffice. 2587 // Once we fix that problem (which is part of a more general "don't look 2588 // in DeclContexts unless we have to" optimization), we can eliminate this. 2589 Entity = Result.getSema().Context.getTranslationUnitDecl(); 2590 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false, 2591 /*InBaseClass=*/false, Consumer, Visited); 2592 } 2593 2594 if (Entity) { 2595 // Lookup visible declarations in any namespaces found by using 2596 // directives. 2597 UnqualUsingDirectiveSet::const_iterator UI, UEnd; 2598 llvm::tie(UI, UEnd) = UDirs.getNamespacesFor(Entity); 2599 for (; UI != UEnd; ++UI) 2600 LookupVisibleDecls(const_cast<DeclContext *>(UI->getNominatedNamespace()), 2601 Result, /*QualifiedNameLookup=*/false, 2602 /*InBaseClass=*/false, Consumer, Visited); 2603 } 2604 2605 // Lookup names in the parent scope. 2606 ShadowContextRAII Shadow(Visited); 2607 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited); 2608} 2609 2610void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, 2611 VisibleDeclConsumer &Consumer, 2612 bool IncludeGlobalScope) { 2613 // Determine the set of using directives available during 2614 // unqualified name lookup. 2615 Scope *Initial = S; 2616 UnqualUsingDirectiveSet UDirs; 2617 if (getLangOptions().CPlusPlus) { 2618 // Find the first namespace or translation-unit scope. 2619 while (S && !isNamespaceOrTranslationUnitScope(S)) 2620 S = S->getParent(); 2621 2622 UDirs.visitScopeChain(Initial, S); 2623 } 2624 UDirs.done(); 2625 2626 // Look for visible declarations. 2627 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 2628 VisibleDeclsRecord Visited; 2629 if (!IncludeGlobalScope) 2630 Visited.visitedContext(Context.getTranslationUnitDecl()); 2631 ShadowContextRAII Shadow(Visited); 2632 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited); 2633} 2634 2635void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 2636 VisibleDeclConsumer &Consumer, 2637 bool IncludeGlobalScope) { 2638 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); 2639 VisibleDeclsRecord Visited; 2640 if (!IncludeGlobalScope) 2641 Visited.visitedContext(Context.getTranslationUnitDecl()); 2642 ShadowContextRAII Shadow(Visited); 2643 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, 2644 /*InBaseClass=*/false, Consumer, Visited); 2645} 2646 2647//---------------------------------------------------------------------------- 2648// Typo correction 2649//---------------------------------------------------------------------------- 2650 2651namespace { 2652class TypoCorrectionConsumer : public VisibleDeclConsumer { 2653 /// \brief The name written that is a typo in the source. 2654 llvm::StringRef Typo; 2655 2656 /// \brief The results found that have the smallest edit distance 2657 /// found (so far) with the typo name. 2658 llvm::SmallVector<NamedDecl *, 4> BestResults; 2659 2660 /// \brief The keywords that have the smallest edit distance. 2661 llvm::SmallVector<IdentifierInfo *, 4> BestKeywords; 2662 2663 /// \brief The best edit distance found so far. 2664 unsigned BestEditDistance; 2665 2666public: 2667 explicit TypoCorrectionConsumer(IdentifierInfo *Typo) 2668 : Typo(Typo->getName()) { } 2669 2670 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass); 2671 void addKeywordResult(ASTContext &Context, llvm::StringRef Keyword); 2672 2673 typedef llvm::SmallVector<NamedDecl *, 4>::const_iterator iterator; 2674 iterator begin() const { return BestResults.begin(); } 2675 iterator end() const { return BestResults.end(); } 2676 void clear_decls() { BestResults.clear(); } 2677 2678 bool empty() const { return BestResults.empty() && BestKeywords.empty(); } 2679 2680 typedef llvm::SmallVector<IdentifierInfo *, 4>::const_iterator 2681 keyword_iterator; 2682 keyword_iterator keyword_begin() const { return BestKeywords.begin(); } 2683 keyword_iterator keyword_end() const { return BestKeywords.end(); } 2684 bool keyword_empty() const { return BestKeywords.empty(); } 2685 unsigned keyword_size() const { return BestKeywords.size(); } 2686 2687 unsigned getBestEditDistance() const { return BestEditDistance; } 2688}; 2689 2690} 2691 2692void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, 2693 bool InBaseClass) { 2694 // Don't consider hidden names for typo correction. 2695 if (Hiding) 2696 return; 2697 2698 // Only consider entities with identifiers for names, ignoring 2699 // special names (constructors, overloaded operators, selectors, 2700 // etc.). 2701 IdentifierInfo *Name = ND->getIdentifier(); 2702 if (!Name) 2703 return; 2704 2705 // Compute the edit distance between the typo and the name of this 2706 // entity. If this edit distance is not worse than the best edit 2707 // distance we've seen so far, add it to the list of results. 2708 unsigned ED = Typo.edit_distance(Name->getName()); 2709 if (!BestResults.empty() || !BestKeywords.empty()) { 2710 if (ED < BestEditDistance) { 2711 // This result is better than any we've seen before; clear out 2712 // the previous results. 2713 BestResults.clear(); 2714 BestKeywords.clear(); 2715 BestEditDistance = ED; 2716 } else if (ED > BestEditDistance) { 2717 // This result is worse than the best results we've seen so far; 2718 // ignore it. 2719 return; 2720 } 2721 } else 2722 BestEditDistance = ED; 2723 2724 BestResults.push_back(ND); 2725} 2726 2727void TypoCorrectionConsumer::addKeywordResult(ASTContext &Context, 2728 llvm::StringRef Keyword) { 2729 // Compute the edit distance between the typo and this keyword. 2730 // If this edit distance is not worse than the best edit 2731 // distance we've seen so far, add it to the list of results. 2732 unsigned ED = Typo.edit_distance(Keyword); 2733 if (!BestResults.empty() || !BestKeywords.empty()) { 2734 if (ED < BestEditDistance) { 2735 BestResults.clear(); 2736 BestKeywords.clear(); 2737 BestEditDistance = ED; 2738 } else if (ED > BestEditDistance) { 2739 // This result is worse than the best results we've seen so far; 2740 // ignore it. 2741 return; 2742 } 2743 } else 2744 BestEditDistance = ED; 2745 2746 BestKeywords.push_back(&Context.Idents.get(Keyword)); 2747} 2748 2749/// \brief Try to "correct" a typo in the source code by finding 2750/// visible declarations whose names are similar to the name that was 2751/// present in the source code. 2752/// 2753/// \param Res the \c LookupResult structure that contains the name 2754/// that was present in the source code along with the name-lookup 2755/// criteria used to search for the name. On success, this structure 2756/// will contain the results of name lookup. 2757/// 2758/// \param S the scope in which name lookup occurs. 2759/// 2760/// \param SS the nested-name-specifier that precedes the name we're 2761/// looking for, if present. 2762/// 2763/// \param MemberContext if non-NULL, the context in which to look for 2764/// a member access expression. 2765/// 2766/// \param EnteringContext whether we're entering the context described by 2767/// the nested-name-specifier SS. 2768/// 2769/// \param CTC The context in which typo correction occurs, which impacts the 2770/// set of keywords permitted. 2771/// 2772/// \param OPT when non-NULL, the search for visible declarations will 2773/// also walk the protocols in the qualified interfaces of \p OPT. 2774/// 2775/// \returns the corrected name if the typo was corrected, otherwise returns an 2776/// empty \c DeclarationName. When a typo was corrected, the result structure 2777/// may contain the results of name lookup for the correct name or it may be 2778/// empty. 2779DeclarationName Sema::CorrectTypo(LookupResult &Res, Scope *S, CXXScopeSpec *SS, 2780 DeclContext *MemberContext, 2781 bool EnteringContext, 2782 CorrectTypoContext CTC, 2783 const ObjCObjectPointerType *OPT) { 2784 if (Diags.hasFatalErrorOccurred() || !getLangOptions().SpellChecking) 2785 return DeclarationName(); 2786 2787 // Provide a stop gap for files that are just seriously broken. Trying 2788 // to correct all typos can turn into a HUGE performance penalty, causing 2789 // some files to take minutes to get rejected by the parser. 2790 // FIXME: Is this the right solution? 2791 if (TyposCorrected == 20) 2792 return DeclarationName(); 2793 ++TyposCorrected; 2794 2795 // We only attempt to correct typos for identifiers. 2796 IdentifierInfo *Typo = Res.getLookupName().getAsIdentifierInfo(); 2797 if (!Typo) 2798 return DeclarationName(); 2799 2800 // If the scope specifier itself was invalid, don't try to correct 2801 // typos. 2802 if (SS && SS->isInvalid()) 2803 return DeclarationName(); 2804 2805 // Never try to correct typos during template deduction or 2806 // instantiation. 2807 if (!ActiveTemplateInstantiations.empty()) 2808 return DeclarationName(); 2809 2810 TypoCorrectionConsumer Consumer(Typo); 2811 2812 // Perform name lookup to find visible, similarly-named entities. 2813 if (MemberContext) { 2814 LookupVisibleDecls(MemberContext, Res.getLookupKind(), Consumer); 2815 2816 // Look in qualified interfaces. 2817 if (OPT) { 2818 for (ObjCObjectPointerType::qual_iterator 2819 I = OPT->qual_begin(), E = OPT->qual_end(); 2820 I != E; ++I) 2821 LookupVisibleDecls(*I, Res.getLookupKind(), Consumer); 2822 } 2823 } else if (SS && SS->isSet()) { 2824 DeclContext *DC = computeDeclContext(*SS, EnteringContext); 2825 if (!DC) 2826 return DeclarationName(); 2827 2828 LookupVisibleDecls(DC, Res.getLookupKind(), Consumer); 2829 } else { 2830 LookupVisibleDecls(S, Res.getLookupKind(), Consumer); 2831 } 2832 2833 // Add context-dependent keywords. 2834 bool WantTypeSpecifiers = false; 2835 bool WantExpressionKeywords = false; 2836 bool WantCXXNamedCasts = false; 2837 bool WantRemainingKeywords = false; 2838 switch (CTC) { 2839 case CTC_Unknown: 2840 WantTypeSpecifiers = true; 2841 WantExpressionKeywords = true; 2842 WantCXXNamedCasts = true; 2843 WantRemainingKeywords = true; 2844 2845 if (ObjCMethodDecl *Method = getCurMethodDecl()) 2846 if (Method->getClassInterface() && 2847 Method->getClassInterface()->getSuperClass()) 2848 Consumer.addKeywordResult(Context, "super"); 2849 2850 break; 2851 2852 case CTC_NoKeywords: 2853 break; 2854 2855 case CTC_Type: 2856 WantTypeSpecifiers = true; 2857 break; 2858 2859 case CTC_ObjCMessageReceiver: 2860 Consumer.addKeywordResult(Context, "super"); 2861 // Fall through to handle message receivers like expressions. 2862 2863 case CTC_Expression: 2864 if (getLangOptions().CPlusPlus) 2865 WantTypeSpecifiers = true; 2866 WantExpressionKeywords = true; 2867 // Fall through to get C++ named casts. 2868 2869 case CTC_CXXCasts: 2870 WantCXXNamedCasts = true; 2871 break; 2872 2873 case CTC_MemberLookup: 2874 if (getLangOptions().CPlusPlus) 2875 Consumer.addKeywordResult(Context, "template"); 2876 break; 2877 } 2878 2879 if (WantTypeSpecifiers) { 2880 // Add type-specifier keywords to the set of results. 2881 const char *CTypeSpecs[] = { 2882 "char", "const", "double", "enum", "float", "int", "long", "short", 2883 "signed", "struct", "union", "unsigned", "void", "volatile", "_Bool", 2884 "_Complex", "_Imaginary", 2885 // storage-specifiers as well 2886 "extern", "inline", "static", "typedef" 2887 }; 2888 2889 const unsigned NumCTypeSpecs = sizeof(CTypeSpecs) / sizeof(CTypeSpecs[0]); 2890 for (unsigned I = 0; I != NumCTypeSpecs; ++I) 2891 Consumer.addKeywordResult(Context, CTypeSpecs[I]); 2892 2893 if (getLangOptions().C99) 2894 Consumer.addKeywordResult(Context, "restrict"); 2895 if (getLangOptions().Bool || getLangOptions().CPlusPlus) 2896 Consumer.addKeywordResult(Context, "bool"); 2897 2898 if (getLangOptions().CPlusPlus) { 2899 Consumer.addKeywordResult(Context, "class"); 2900 Consumer.addKeywordResult(Context, "typename"); 2901 Consumer.addKeywordResult(Context, "wchar_t"); 2902 2903 if (getLangOptions().CPlusPlus0x) { 2904 Consumer.addKeywordResult(Context, "char16_t"); 2905 Consumer.addKeywordResult(Context, "char32_t"); 2906 Consumer.addKeywordResult(Context, "constexpr"); 2907 Consumer.addKeywordResult(Context, "decltype"); 2908 Consumer.addKeywordResult(Context, "thread_local"); 2909 } 2910 } 2911 2912 if (getLangOptions().GNUMode) 2913 Consumer.addKeywordResult(Context, "typeof"); 2914 } 2915 2916 if (WantCXXNamedCasts && getLangOptions().CPlusPlus) { 2917 Consumer.addKeywordResult(Context, "const_cast"); 2918 Consumer.addKeywordResult(Context, "dynamic_cast"); 2919 Consumer.addKeywordResult(Context, "reinterpret_cast"); 2920 Consumer.addKeywordResult(Context, "static_cast"); 2921 } 2922 2923 if (WantExpressionKeywords) { 2924 Consumer.addKeywordResult(Context, "sizeof"); 2925 if (getLangOptions().Bool || getLangOptions().CPlusPlus) { 2926 Consumer.addKeywordResult(Context, "false"); 2927 Consumer.addKeywordResult(Context, "true"); 2928 } 2929 2930 if (getLangOptions().CPlusPlus) { 2931 const char *CXXExprs[] = { 2932 "delete", "new", "operator", "throw", "typeid" 2933 }; 2934 const unsigned NumCXXExprs = sizeof(CXXExprs) / sizeof(CXXExprs[0]); 2935 for (unsigned I = 0; I != NumCXXExprs; ++I) 2936 Consumer.addKeywordResult(Context, CXXExprs[I]); 2937 2938 if (isa<CXXMethodDecl>(CurContext) && 2939 cast<CXXMethodDecl>(CurContext)->isInstance()) 2940 Consumer.addKeywordResult(Context, "this"); 2941 2942 if (getLangOptions().CPlusPlus0x) { 2943 Consumer.addKeywordResult(Context, "alignof"); 2944 Consumer.addKeywordResult(Context, "nullptr"); 2945 } 2946 } 2947 } 2948 2949 if (WantRemainingKeywords) { 2950 if (getCurFunctionOrMethodDecl() || getCurBlock()) { 2951 // Statements. 2952 const char *CStmts[] = { 2953 "do", "else", "for", "goto", "if", "return", "switch", "while" }; 2954 const unsigned NumCStmts = sizeof(CStmts) / sizeof(CStmts[0]); 2955 for (unsigned I = 0; I != NumCStmts; ++I) 2956 Consumer.addKeywordResult(Context, CStmts[I]); 2957 2958 if (getLangOptions().CPlusPlus) { 2959 Consumer.addKeywordResult(Context, "catch"); 2960 Consumer.addKeywordResult(Context, "try"); 2961 } 2962 2963 if (S && S->getBreakParent()) 2964 Consumer.addKeywordResult(Context, "break"); 2965 2966 if (S && S->getContinueParent()) 2967 Consumer.addKeywordResult(Context, "continue"); 2968 2969 if (!getSwitchStack().empty()) { 2970 Consumer.addKeywordResult(Context, "case"); 2971 Consumer.addKeywordResult(Context, "default"); 2972 } 2973 } else { 2974 if (getLangOptions().CPlusPlus) { 2975 Consumer.addKeywordResult(Context, "namespace"); 2976 Consumer.addKeywordResult(Context, "template"); 2977 } 2978 2979 if (S && S->isClassScope()) { 2980 Consumer.addKeywordResult(Context, "explicit"); 2981 Consumer.addKeywordResult(Context, "friend"); 2982 Consumer.addKeywordResult(Context, "mutable"); 2983 Consumer.addKeywordResult(Context, "private"); 2984 Consumer.addKeywordResult(Context, "protected"); 2985 Consumer.addKeywordResult(Context, "public"); 2986 Consumer.addKeywordResult(Context, "virtual"); 2987 } 2988 } 2989 2990 if (getLangOptions().CPlusPlus) { 2991 Consumer.addKeywordResult(Context, "using"); 2992 2993 if (getLangOptions().CPlusPlus0x) 2994 Consumer.addKeywordResult(Context, "static_assert"); 2995 } 2996 } 2997 2998 // If we haven't found anything, we're done. 2999 if (Consumer.empty()) 3000 return DeclarationName(); 3001 3002 // Only allow a single, closest name in the result set (it's okay to 3003 // have overloads of that name, though). 3004 DeclarationName BestName; 3005 NamedDecl *BestIvarOrPropertyDecl = 0; 3006 bool FoundIvarOrPropertyDecl = false; 3007 3008 // Check all of the declaration results to find the best name so far. 3009 for (TypoCorrectionConsumer::iterator I = Consumer.begin(), 3010 IEnd = Consumer.end(); 3011 I != IEnd; ++I) { 3012 if (!BestName) 3013 BestName = (*I)->getDeclName(); 3014 else if (BestName != (*I)->getDeclName()) 3015 return DeclarationName(); 3016 3017 // \brief Keep track of either an Objective-C ivar or a property, but not 3018 // both. 3019 if (isa<ObjCIvarDecl>(*I) || isa<ObjCPropertyDecl>(*I)) { 3020 if (FoundIvarOrPropertyDecl) 3021 BestIvarOrPropertyDecl = 0; 3022 else { 3023 BestIvarOrPropertyDecl = *I; 3024 FoundIvarOrPropertyDecl = true; 3025 } 3026 } 3027 } 3028 3029 // Now check all of the keyword results to find the best name. 3030 switch (Consumer.keyword_size()) { 3031 case 0: 3032 // No keywords matched. 3033 break; 3034 3035 case 1: 3036 // If we already have a name 3037 if (!BestName) { 3038 // We did not have anything previously, 3039 BestName = *Consumer.keyword_begin(); 3040 } else if (BestName.getAsIdentifierInfo() == *Consumer.keyword_begin()) { 3041 // We have a declaration with the same name as a context-sensitive 3042 // keyword. The keyword takes precedence. 3043 BestIvarOrPropertyDecl = 0; 3044 FoundIvarOrPropertyDecl = false; 3045 Consumer.clear_decls(); 3046 } else if (CTC == CTC_ObjCMessageReceiver && 3047 (*Consumer.keyword_begin())->isStr("super")) { 3048 // In an Objective-C message send, give the "super" keyword a slight 3049 // edge over entities not in function or method scope. 3050 for (TypoCorrectionConsumer::iterator I = Consumer.begin(), 3051 IEnd = Consumer.end(); 3052 I != IEnd; ++I) { 3053 if ((*I)->getDeclName() == BestName) { 3054 if ((*I)->getDeclContext()->isFunctionOrMethod()) 3055 return DeclarationName(); 3056 } 3057 } 3058 3059 // Everything found was outside a function or method; the 'super' 3060 // keyword takes precedence. 3061 BestIvarOrPropertyDecl = 0; 3062 FoundIvarOrPropertyDecl = false; 3063 Consumer.clear_decls(); 3064 BestName = *Consumer.keyword_begin(); 3065 } else { 3066 // Name collision; we will not correct typos. 3067 return DeclarationName(); 3068 } 3069 break; 3070 3071 default: 3072 // Name collision; we will not correct typos. 3073 return DeclarationName(); 3074 } 3075 3076 // BestName is the closest viable name to what the user 3077 // typed. However, to make sure that we don't pick something that's 3078 // way off, make sure that the user typed at least 3 characters for 3079 // each correction. 3080 unsigned ED = Consumer.getBestEditDistance(); 3081 if (ED == 0 || !BestName.getAsIdentifierInfo() || 3082 (BestName.getAsIdentifierInfo()->getName().size() / ED) < 3) 3083 return DeclarationName(); 3084 3085 // Perform name lookup again with the name we chose, and declare 3086 // success if we found something that was not ambiguous. 3087 Res.clear(); 3088 Res.setLookupName(BestName); 3089 3090 // If we found an ivar or property, add that result; no further 3091 // lookup is required. 3092 if (BestIvarOrPropertyDecl) 3093 Res.addDecl(BestIvarOrPropertyDecl); 3094 // If we're looking into the context of a member, perform qualified 3095 // name lookup on the best name. 3096 else if (!Consumer.keyword_empty()) { 3097 // The best match was a keyword. Return it. 3098 return BestName; 3099 } else if (MemberContext) 3100 LookupQualifiedName(Res, MemberContext); 3101 // Perform lookup as if we had just parsed the best name. 3102 else 3103 LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, 3104 EnteringContext); 3105 3106 if (Res.isAmbiguous()) { 3107 Res.suppressDiagnostics(); 3108 return DeclarationName(); 3109 } 3110 3111 if (Res.getResultKind() != LookupResult::NotFound) 3112 return BestName; 3113 3114 return DeclarationName(); 3115} 3116