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